Search code examples
phppreg-replacedeprecatedpreg-replace-callback

Replace preg_replace() with `e` modifier with call of preg_replace_callback() to fix the invalid character count in a serialized string


How can I update this code :

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

with the preg_replace_callback function?

Thanks.


Solution

  • preg_replace_callback() is very similar to preg_replace(), except parameter 2 is a callable function that takes $matches as a parameter. Don't forget to remove the /e modifier, since we aren't executing anything.

    $array = array(
        's:1:"test";',
        's:2:"one more";',
    );
    
    $data = preg_replace_callback('!s:(\d+):"(.*?)";!', function($matches) {
        $string = $matches[2];
        $length = strlen($string);
        return 's:' . $length . ':"' . $string . '";';
    }, $array);
    
    print_r($data);
    // Array ( [0] => s:4:"test"; [1] => s:8:"one more"; )