[英]PHP's preg_replace where the replacement is an arbitrary function of the match
假设我想将“ foo”的出现替换为“ oof”:
$s = "abc foo bar";
echo preg_replace('/(foo)/', strrev("$1"), $s);
代替“ abc oof bar
”,我得到“ abc 1$ bar
”。 换句话说,它将文字字符串“ $ 1”传递给strrev()函数,而不是正则表达式匹配项“ foo”。
解决以上代码中此问题的最佳方法是什么?
传递/e
标志。
echo preg_replace('/(foo)/e', 'strrev("\\1")', $s);
一个更安全的选择是使用preg_replace_callback
。
function revMatch ($matches) {
return strrev($matches[1]);
}
...
echo preg_replace_callback('/(foo)/', "revMatch", $s);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.