在 PHP 中的 preg_replace 中使用 $ 变量 [英] Using $ variables in preg_replace in PHP
问题描述
嗯...如何在调用 preg_replace 时使用变量?
Ummm... how do I use variables in a call to preg_replace?
这不起作用:
foreach($numarray as $num => $text)
{
$patterns[] = '/<ces>(.*?)\+$num(.*?)<\/ces>/';
$replacements[] = '<ces>$1<$text/>$2</ces>';
}
是的,$num
前面有一个加号.是的,我想将 $num 标记为 <$text/>
".
Yes, the $num
is preceeded by a plus sign. Yes, I want to "tag the $num as <$text/>
".
推荐答案
您的替换模式看起来不错,但由于您在匹配模式中使用了单引号,因此您的 $num 变量不会插入其中.相反,尝试
Your replacement pattern looks ok, but as you've used single quotes in the matching pattern, your $num variable won't be inserted into it. Instead, try
$patterns[] = '/<ces>(.*?)\+'.$num.'(.*?)<\/ces>/';
$replacements[] = '<ces>$1<'.$text.'/>$2</ces>';
另请注意,从这样的未知"输入构建模式时,通常最好使用 preg_quote一>.例如
Also note that when building up a pattern from "unknown" inputs like this, it's usually a good idea to use preg_quote. e.g.
$patterns[] = '/<ces>(.*?)\+'.preg_quote($num).'(.*?)<\/ces>/';
虽然我猜给定变量名,在你的情况下它总是数字.
Though I guess given the variable name it's always numeric in your case.
这篇关于在 PHP 中的 preg_replace 中使用 $ 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!