Replace deprecated preg_replace /e with preg_replace_callback [duplicate]

試著忘記壹切 提交于 2019-11-26 05:34:47

问题


This question already has an answer here:

  • Replace preg_replace() e modifier with preg_replace_callback 3 answers
$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:

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead

How can I replace the code with preg_replace_callback()?


回答1:


You can use an anonymous function to 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 \".



来源:https://stackoverflow.com/questions/19245205/replace-deprecated-preg-replace-e-with-preg-replace-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!