PHP- preg_replace on hex char
-
21-04-2021 - |
Frage
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?
Lösung
$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;
Andere Tipps
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>');
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow