PHP preg_replace alternative

徘徊边缘 提交于 2019-12-13 00:54:46

问题


We're currently getting a preg_replace error message on our site due to deprecation.

Our code is as follows:

$out = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $data);

Any suggestions on how this can be replaced with non-deprecated code?


回答1:


preg_ is not deprecated. It is just /e (as of PHP 5.5):

The /e modifier is deprecated. Use preg_replace_callback() instead. See the PREG_REPLACE_EVAL documentation for additional information about security risks.

and as preg_replace_callback() is almost identical to preg_replace() with exception that it uses callback instead of replacement, update of your code should be quick homework.




回答2:


You're using the modifiers s and e. Copied directly from Deprecated feature sin PHP 5.5.x:

The preg_replace() /e modifier is now deprecated. Instead, use the preg_replace_callback() function.




回答3:


In this case, I found this "callback_function" that works fine:

$fixed_text = preg_replace_callback ( '!s:(\d+):"(.*?)";!',
function($m) {
       return ($m[1] == strlen($m[2])) ? $m[0] : 's:' . strlen($m[2]) . ':"' . $m[2] . '";';
},
$text);


来源:https://stackoverflow.com/questions/21000320/php-preg-replace-alternative

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