Question

How to use preg_replace to convert only matching hex values into text representation of hex?

$string = 'abcd'.hex2bin(23).'abc'.hex2bin(24);

For example str_replace('/[\x20-\x25]/', 'what here?', $string) would get output like:

abcd[HEX:23]abc[HEX:24]

What exactly I want to do: I'm looking for hidden characters, and want to display their hex values.

Was it helpful?

Solution

You need something like preg_replace_callback() to have a callback called against all matches.

Try:

$string = 'abcd'.hex2bin(23).'abc'.hex2bin(24);

$text = preg_replace_callback('/[\\x20-\\x25]/', function($matches) {
    $string = bin2hex($matches[0]);
    return "[HEX:{$string}]";
}, $string);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top