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

如果您需要对 url 进行一些数学、计算、查找等操作,您可以使用preg_replace_callback。您只需将回调函数指定为替换值,该函数在调用时一次传递每个匹配项,并且该函数的返回值是替换值。

<?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 回答
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 回答