在PHP中的preg_replace中使用$ variables
-
05-07-2019 - |
题
嗯......如何在调用preg_replace时使用变量?
这不起作用:
foreach($numarray as $num => $text)
{
$patterns[] = '/<ces>(.*?)\+$num(.*?)<\/ces>/';
$replacements[] = '<ces>$1<$text/>$2</ces>';
}
是的,$num
前面有一个加号。是的,我想要<!>“; tag the $num as <$text/>
<!>”;
解决方案
您的替换模式看起来不错,但由于您在匹配模式中使用了单引号,因此不会将$ num变量插入其中。相反,尝试
$patterns[] = '/<ces>(.*?)\+'.$num.'(.*?)<\/ces>/';
$replacements[] = '<ces>$1<'.$text.'/>$2</ces>';
另请注意,从<!>“未知<!>”构建模式时像这样的输入,使用 preg_quote 通常是个好主意。 e.g。
$patterns[] = '/<ces>(.*?)\+'.preg_quote($num).'(.*?)<\/ces>/';
虽然我认为给定变量名称,但在你的情况下它总是数字。
其他提示
变量只会在用双引号声明的字符串。所以要么使用双引号:
$patterns[] = "/<ces>(.*?)\\+$num(.*?)<\\/ces>/";
$replacements[] = "<ces>$1<$text/>$2</ces>";
或者使用字符串连接:
$patterns[] = '/<ces>(.*?)\+'.$num.'(.*?)<\/ces>/';
$replacements[] = '<ces>$1<'.$text.'/>$2</ces>';
如果您的变量可能包含正则表达式元字符,您还应该查看 preg_quote
。
不隶属于 StackOverflow