【问题标题】:preg_replace and array valuespreg_replace 和数组值
【发布时间】:2012-07-17 23:07:01
【问题描述】:

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

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

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    这有什么问题?

    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>
    

    【讨论】:

    • 我必须使用数组来做一些计算。有什么方法可以将代码中的 $1 传递给变量吗?
    • 使用 preg_match_all 来解决这个问题
    【解决方案2】:

    如果您需要对 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

    【讨论】:

      【解决方案3】:
      $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 行代码中做同样的事情时,那将是非常愚蠢的。
      • 因为我必须计算 url 的确切路径。
      • 你能给出一个完整的例子来说明预期的结果吗?包括不同的 URL。
      • 可能的答案是 15 和 26
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多