php 用 preg_replace_callback 替换已弃用的 preg_replace /e
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19245205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Replace deprecated preg_replace /e with preg_replace_callback
提问by dima.h
$result = preg_replace(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\1\/\2\}/iseU",
"CallFunction('\1','\2','\3','\4','\5')",
$result
);
The above code gives a deprecation warning after upgrading to PHP 5.5:
以上代码在升级到 PHP 5.5 后给出了弃用警告:
Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead
已弃用:preg_replace():不推荐使用 /e 修饰符,请改用 preg_replace_callback
How can I replace the code with preg_replace_callback()
?
我怎样才能用 替换代码preg_replace_callback()
?
回答by NikiC
You can use an anonymous functionto pass the matches to your function:
您可以使用匿名函数将匹配项传递给您的函数:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\1\/\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
除了速度更快之外,这还可以正确处理字符串中的双引号。您当前使用的代码/e
会将双引号"
转换为\"
.