0

中括弧 ('{}') 内のすべての数値をハイパーリンクに変換する必要があります。問題は、文字列に複数のパターンを含めることができるということです。

$text = 'the possible answers are {1}, {5}, and {26}';
preg_match_all( '#{([0-9]+)}#', $text, $matches );

出力配列はこのようなものです

Array ( 
[0] => Array ( [0] => {1} [1] => {5} [2] => {26} ) 
[1] => Array ( [0] => 1 [1] => 5 [2] => 26 ) 
)

これが私の現在のコードです。

$number=0;
return preg_replace('#{([0-9]+)}#','<a href="#$1">>>'.$matches[1][$number].'</a>',$text);
$number++;

しかし、出力は次のようになります

The possible answers are
<a href="#1">1</a>, <a href="#5">1</a>, and <a href="#26">1</a>

'1' ($matches[1][0]) のみがフェッチされています。

これを修正するにはどうすればよいですか?

4

3 に答える 3

0

これの何が問題なのですか?

return preg_replace('#{([0-9]+)}#','<a href="#$1">$1</a>', $text);

これを出力します:

<a href="#1">1</a>, <a href="#5">5</a>, and <a href="#26">26</a>
于 2012-07-17T23:24:54.790 に答える
0
$text = 'the possible answers are {1}, {5}, and {26}';
$text = preg_replace('/\{(\d+)\}/i', '<a href="#\\1">\\1</a>', $text);
var_dump($text);

string(89) "the possible answers are <a href="#1">1</a>, <a href="#5">5</a>, and <a href="#26">26</a>"

編集(配列で回答):

$text = 'the possible answers are {1}, {5}, and {26}';
if (($c = preg_match_all('/\{(\d+)\}/i', $text, $matches)) > 0)
{
    for ($i = 0; $i < $c; $i++)
    {
        // calculate here ... and assign to $link
        $text = str_replace($matches[0][$i], '<a href="'.$link.'"'>'.$matches[1][$i].'</a>', $text);
    }
}
于 2012-07-17T23:20:32.367 に答える
0

URLの数学、計算、検索などを行う必要がある場合は、preg_replace_callbackを使用できます。コールバック関数を置換値として指定するだけで、関数は呼び出されるたびに一致するものを 1 つずつ渡され、関数からの戻り値が置換値になります。

<?php
$text = 'the possible answers are {1}, {5}, and {26}';

$text = preg_replace_callback('#\{([0-9]+)\}#',
    function($matches){
        //do some calculations
        $num = $matches[1] * 5;
        return "<a href='#{$matches[1]}'>{$num}</a>";
    }, $text);
var_dump($text);
?>

http://codepad.viper-7.com/zM7dwm

于 2012-07-17T23:45:35.947 に答える