How can I replace UTF-8 encoded sequences in a PHP string with their actual characters?

Solution:

If you have a string with single-byte hex escapes (like \x41\x42), you can convert them to actual characters using a regular expression with preg_replace():


$var = '\x41\x42\x43'; // Example string

echo preg_replace(
    "#(\\\x[0-9A-F]{2})#e",
    "chr(hexdec('\\1'))",
    $var
);

Note:

The e modifier in preg_replace() evaluates the replacement as PHP code.

In modern PHP versions (7.0+), the e modifier is deprecated, so it’s better to use a callback with preg_replace_callback().