php将preg_replace转换为preg_replace_callback

时间:2022-10-11 22:25:47

I'm working on this old code, and ran across this - which fails:

我正在研究这个旧代码,并遇到了这个 - 它失败了:

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

It tells me that preg_replace e modifier is deprecated, and to use preg_replace_callback instead.

它告诉我不推荐使用preg_replace e修饰符,而是使用preg_replace_callback。

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

根据我的理解,我应该替换's:'。strlen('$ 2')。':\“$ 2 \”;'部分具有回调功能,可以在匹配时进行替换。

What I DON'T quite get, is exactly what the regexp is doing that I'll be replacing. It's part of a bit to take php serialized data stuffed in a database field (dumb, I know ...) with broken length fields and fix them for reinsertion.

我不会得到的,正是正在进行的正在进行的我将要取代的东西。将数据库字段中填充的php序列化数据(哑巴,我知道......)与长度较短的字段进行处理并修复它们以进行重新插入是一部分。

So can anybody explain what that bit is doing, or what I should replace it with?

那么任何人都可以解释那一点在做什么,或者我应该用它替换它?

1 个解决方案

#1


6  

Use

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

The !e modifier must be removed. $2 backreferences must be replaced with $m[2] where $m is a match object containing match value and submatches and that is passed to the anonymous function inside preg_replace_callback.

必须删除!e修饰符。 $ 2反向引用必须替换为$ m [2],其中$ m是包含匹配值和子匹配的匹配对象,并传递给preg_replace_callback内的匿名函数。

Here is a demo where the digits after s: get replaced with the $m[2] length:

这是一个演示,其中s:后的数字被替换为$ 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";

#1


6  

Use

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

The !e modifier must be removed. $2 backreferences must be replaced with $m[2] where $m is a match object containing match value and submatches and that is passed to the anonymous function inside preg_replace_callback.

必须删除!e修饰符。 $ 2反向引用必须替换为$ m [2],其中$ m是包含匹配值和子匹配的匹配对象,并传递给preg_replace_callback内的匿名函数。

Here is a demo where the digits after s: get replaced with the $m[2] length:

这是一个演示,其中s:后的数字被替换为$ 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";