Question

i have a string, like this:

'<indirizzo>Via Universit\E0 4</indirizzo>'

Whit HEX char... i need string become:

'<indirizzo>Via Università 4</indirizzo>'

So, i use:
$text= preg_replace('/(\\\\)([a-f0-9]{2})/imu', chr(hexdec("$2")), $text);

But dont work because hexdec dont use value of $2 (that is 'E0'), but use only value '2'. So hexdex("2") is "2" and chr("2") isnt "à"

What can i do?

Was it helpful?

Solution

$text='<indirizzo>Via Universit\E0 4</indirizzo>';

function cb($match) {
    return html_entity_decode('&#'.hexdec($match[1]).';');
}
$text= preg_replace_callback('/\\\\([a-f0-9]{2})/imu', 'cb', $text);

echo $text;

OTHER TIPS

You need to specify your chr(hexdec()) as a callback. Just calling those functions and suppling the result as parameter to preg_replace doesn't do it.

preg_replace_callback('/\\\([a-f0-9]{2})/imu',
                      function ($match) { return chr(hexdec($match[1])); },
                      $text)

Having said that, there are probably better ways to do what you want to do overall.

You could also use

<?php
$str = preg_replace('/\\([a-f0-9]{2})/imue', '"\x$1"', '<indirizzo>Via Universit\E0 4</indirizzo>');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top