5

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

johnlemon
  • 20,761
  • 42
  • 119
  • 178

3 Answers3

7
function hexStringToString($hex) {
    return pack('H*', $hex);
}
chaos
  • 122,029
  • 33
  • 303
  • 309
  • really strange, can you explain ? – johnlemon Oct 03 '12 at 20:57
  • 3
    @danip: pack() and unpack() are PHP's functions for pushing data in and out of binary strings. `H*` means "any number of hexadecimal octets, high nybble first". See http://php.net/manual/en/function.pack.php. – chaos Oct 03 '12 at 21:38
  • If his hex code was instead expressed as %C2%AE what should the value of H* be changed to? – Grant_Bailey Feb 21 '15 at 10:06
  • @chaos could you tell me how can this be done in reverse? I mean give "®" and get "C2AE" . Using the pack function. (Ive read other questions + answers about this, I wanna know how can this be achieved using amazing `pack` function) thnx – TechLife Apr 12 '15 at 20:49
  • @TechLife `unpack('H*', '®')`, which has the result `array('c2ae')`. – chaos Apr 26 '15 at 09:00
1

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!

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Halcyon
  • 1,376
  • 1
  • 15
  • 22
  • Your answer looked promising, but I still can't figure out how to echo ☑ with the http://www.fileformat.info/info/unicode/char/fe0e/index.htm after it so that it forces it to display as plain text rather than an emoji. Do you know? Thanks. – Ryan Feb 21 '19 at 15:27
  • 1
    Not sure if you are still looking, but the checkmark in box [ballot box in check on this page](https://en.wikipedia.org/wiki/Check_mark) should be unicode 2611, so PHP should be able to echo it with `echo "\u{2611}";` Hopefully that helps! – Halcyon Feb 28 '19 at 13:21
  • Thanks. I ended up moving it to SCSS like this `content: "☑\FE0E"` and needed to use EmojiSymbols font (https://stackoverflow.com/questions/32915485/how-to-prevent-unicode-characters-from-rendering-as-emoji-in-html-from-javascrip#comment73067475_38452396) – Ryan Feb 28 '19 at 14:46
0

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);
?>
Alexandr
  • 154
  • 1
  • 7