preg_ replace和数组值


preg_replace and array values

我需要将花括号("{}")内的每个数字转换为超链接。问题是,字符串可以包含多个模式。

$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])。

我该如何解决这个问题?

这有什么问题?

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>

如果你需要做一些数学、计算、查找。。。对于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

$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);
    }
}