【问题标题】:Using $ variables in preg_replace in PHP在 PHP 的 preg_replace 中使用 $ 变量
【发布时间】:2010-11-26 21:52:05
【问题描述】:

嗯...如何在调用 preg_replace 时使用变量?

这不起作用:

foreach($numarray as $num => $text)
    {
        $patterns[] = '/<ces>(.*?)\+$num(.*?)<\/ces>/';
        $replacements[] = '<ces>$1<$text/>$2</ces>';
    }

是的,$num 前面有一个加号。是的,我想“tag the $num as &lt;$text/&gt;”。

【问题讨论】:

    标签: php variables preg-replace


    【解决方案1】:

    您的替换模式看起来不错,但是由于您在匹配模式中使用了单引号,因此您的 $num 变量不会插入其中。相反,尝试

    $patterns[] = '/<ces>(.*?)\+'.$num.'(.*?)<\/ces>/';
    $replacements[] = '<ces>$1<'.$text.'/>$2</ces>';
    

    另请注意,当从这样的“未知”输入构建模式时,使用preg_quote 通常是个好主意。例如

    $patterns[] = '/<ces>(.*?)\+'.preg_quote($num).'(.*?)<\/ces>/';
    

    虽然我猜给定变量名,但在你的情况下它总是数字。

    【讨论】:

    • 感谢 Gumbo,Paul - 您的意见都提供了帮助!
    【解决方案2】:

    变量只会在strings declared with double quotes 中展开。所以要么使用双引号:

    $patterns[]     = "/<ces>(.*?)\\+$num(.*?)<\\/ces>/";
    $replacements[] = "<ces>$1<$text/>$2</ces>";
    

    或者使用字符串连接:

    $patterns[]     = '/<ces>(.*?)\+'.$num.'(.*?)<\/ces>/';
    $replacements[] = '<ces>$1<'.$text.'/>$2</ces>';
    

    如果您的变量可能包含正则表达式元字符,您还应该查看preg_quote

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多