Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from utf-8 hex code to character in PHP

Tags:

php

utf-8

I have the hex code c2ae, how to I convert this to the UTF-8 character: ®. I need a generic and SIMPLE solution for any hex code.

Update: this should work for any utf-8 hex code like d0a6

like image 590
johnlemon Avatar asked Oct 03 '12 19:10

johnlemon


2 Answers

function hexStringToString($hex) {
    return pack('H*', $hex);
}
like image 79
chaos Avatar answered Nov 03 '22 08:11

chaos


I'm sure you must have found the solution since you asked this 4 years ago, but I hate finding unanswered questions on Google when I am looking for things.

You can create a string that includes hex characters in PHP using:

$string = "\xc2\xae";
$string2 = "\xd0\xa6";
echo $string;
echo $string2;

Which will output ®Ц.

The language reference for PHP [is here under header "Double Quoted"].

You are also able to use octal strings using \22 syntax and in PHP7 unicode code point support was added using \u syntax. This one requires having {} around the code, as in: \u{1000}.

Happy coding!

like image 1
Halcyon Avatar answered Nov 03 '22 08:11

Halcyon