Php converts preg_replace to preg_replace_callback

I am working on this old code and come across this - which fails:

preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $sObject);

He tells me that the preg_replace e modifier is deprecated and uses preg_replace_callback instead.

From what I understand, I have to replace the part 's:'.strlen('$2').':\"$2\";'with a callback function that does the replacement in the match.

What I DO NOT ALLOW is what the regular expression does, which I will replace. This is part of a bit to accept php serialized data filled in a database field (dumb, I know ...) with broken length fields and correct them for re-entry.

So can someone explain what this bit is doing, or what should I replace?

+4
source share
1 answer

Using

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

The modifier !emust be removed. $2backlinks should be replaced by $m[2], where $mis the correspondence object containing the match value and the submatrix, and which is passed to the anonymous function inside preg_replace_callback.

Here is a daemon where the numbers after s:are replaced by the length $m[2]:

$sObject = 's:100:"word";';
$res = preg_replace_callback('!s:(\d+):"(.*?)";!', function($m) {
      return 's:' . strlen($m[2]) . ':"' . $m[2] . '";';
}, $sObject);
echo $res; // => s:4:"word";
+6
source

Source: https://habr.com/ru/post/1627864/


All Articles