PHP preg_replace alternative

2019-07-29 04:12发布

问题:

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);