Search code examples
phppreg-replacepreg-replace-callback

Replace preg_replace through preg_replace_callback


I have a PHP library here and I want to replace preg_replace with preg_replace_callback.

This is the line:

preg_replace("/=([0-9A-F][0-9A-F])/e", 'chr(hexdec("$1"))', $l)

and this is what I did:

preg_replace_callback("/=([0-9A-F][0-9A-F])/", function($m) { return chr(hexdec($m["$1"])); }, $line);

But it didn't work. I still don't understand how preg_replace_callback works. I also looked into many other threads.

Can anyone help me please.

Thank you very much in advance!


Solution

  • You need to use $m[1] to access the second element in the $m array:

    preg_replace_callback("/=([0-9A-F][0-9A-F])/", function($m) { return  
        chr(hexdec($m[1])); }, $line
    );
    

    See PHP demo.