Replace utf8 literals in string

I am getting a string from an external service with some utf8 literal.

$a = $param1;
echo $a;

\xe7\xe3

      

How can I convert $ a (utf8 string with 8 characters) to 'çã'?

I know I can use strtr with a lookup map, but I think there is perhaps a better way.

To simplify the example, I have a simple web page:

<?php
echo '<html><body>'.$_GET['aa'].'</body></html>';

      

And I call it a parameter ?aa=\xe7\xe3

It is displayed in the browser \xe7\xe3

, but I want to show çã

as if I have declared with double quotes "\xe7\xe3"

.

+3


source to share


1 answer


Using the hint from the comments, I ended up with a little algorithm that works for me:



function decode_code($code){
    return preg_replace_callback(
        "@\\\(x)?([0-9a-f]{2,3})@",
        function($m){
            return utf8_encode(chr($m[1]?hexdec($m[2]):octdec($m[2])));
        },
        $code
   );
}

      

0


source







All Articles