PHP preg_replace alternative

2019-07-29 04:10发布

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?

3条回答
Lonely孤独者°
2楼-- · 2019-07-29 04:58

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);
查看更多
Summer. ? 凉城
3楼-- · 2019-07-29 05:06

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.

查看更多
对你真心纯属浪费
4楼-- · 2019-07-29 05:13

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.

查看更多
登录 后发表回答