johnlemon
johnlemon

Reputation: 21509

Convert from utf-8 hex code to character in PHP

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

Upvotes: 5

Views: 8731

Answers (3)

Alexandr
Alexandr

Reputation: 172

First you need to install the PHP extension "mbstring". I have XAMPP installed on Windows and everything is installed by default. Next, we use the function starting with mb_, in our case mb_chr().

example:

<?php
echo mb_chr(0x1F621);
?>

Upvotes: 0

Halcyon
Halcyon

Reputation: 1429

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!

Upvotes: 1

chaos
chaos

Reputation: 124345

function hexStringToString($hex) {
    return pack('H*', $hex);
}

Upvotes: 8

Related Questions