2016-08-22 2 views
1

私のサイトでは、ユーザーはダブルスターのようなリンクを与えることができます:**http://www.google.com**preg_replace()を使用してこのリンクを強調したいと思います。私は正確なリンクをキャッチすることができますが、私はこのリンクの最初の10文字を<a></a>タグの中央に置いて欲しいです。相続人は、コード一致する文字列の最初の10文字を取得--- PHPの正規表現

$str = "http://www.example.com/dnvjndjnvjd"; 
$str = preg_replace('/\*\*(\S+)\*\*/', '<a href="$1">?#right there i want first 10 chracter of $1</a>', $str); 
+1

複雑である必要はありません。['substr()'](http://php.net/manual/en/function.substr.php) –

+0

代わりに$ strを置き換えて出力しますか? – Aaron

+2

preg_replace_callbackを使用して、匿名関数内で一致をトリムします。 –

答えて

0

私は最善の方法は、@ chris85のようだと思う氏は述べています: $str = '**http://example.com/dnvjndjnvjd**'; echo preg_replace('/\*{2}([^\*]{10}).*\*{2}/', '$1', $str);

0

使用preg_replace_callback()

<?php 

$string = "There is an URL in the middle of nowhere: **http://www.example.com/dnvjndjnvjd** and here's another one **http://www.example.com/ddadadada**"; 

$regex = '~\*{2}(https?://(?:www\.)?(\S+))\*{2}~'; 

$string = preg_replace_callback($regex, 
    function($match) { 
     return "<a href='{$match[1]}'>" . substr($match[2], 0, 10) . "</a>"; 
    }, 
    $string); 

echo $string; 
?> 


a demo on ideone.comを参照してください。

0

これは何か?

<?php 
$str = "The magic of regex: **http://www.wizards.net/abracadabra** 
can be nerdy stuff **http://www.muggles.com/technology**"; 
$pattern = '/\*{2}(https?:\/\/([^*]{10})[^*]*?)\*{2}/'; 
$replacement = '<a href="$1">$2</a>'; 
echo preg_replace($pattern, $replacement, $str); 

出力:

The magic of regex: <a href="http://www.wizards.net/abracadabra">www.wizard</a> 
can be nerdy stuff <a href="http://www.muggles.com/technology">www.muggle</a> 
0

だからキャプチャグループ($1で置き換える)で全体の事をキャプチャして、最初の10を捕獲するサブグループを持っている($2と交換してください) :

$str = preg_replace('/\*\*((\S{10})\S*)\*\*/', '<a href="$1">$2</a>', $str); 

Regular expression visualization

Debuggex Demo

に注意してくださいしかし、複数のhttp://www.domain.comスタイルのエントリのみ10文字で、あなただけの非常にわかりやすいされていない、http://wwwを取得します。

関連する問題