preg_replace和数组值

时间:2012-07-17 23:07:02

标签: php regex arrays preg-replace preg-match

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

$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'($匹配[1] [0])。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分: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);
    }
}

答案 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>

答案 2 :(得分:0)

如果你需要为网址做一些数学,计算,查找等,你可以使用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