Daksh Agarwal
Daksh Agarwal

Reputation: 44

Create UTF-8 code from dynamic Unicode in PHP

I am making a dynamic Unicode icon in PHP. I want the UTF-8 code of the Unicode icon.

So far I have done:

$value = "1F600";
$emoIcon = "\u{$value}";

$emoIcon = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $emoIcon);
echo $emoIcon; //output 😀
$hex=bin2hex($emoIcon);
echo $hex;  // output 26237831463630303b
$hexVal=chunk_split($hex,2,"\\x");
var_dump($hexVal);  // output  26\x23\x78\x31\x46\x36\x30\x30\x3b\x
$result= "\\x" . substr($hexVal,0,-2);
var_dump($result);    // output  \x26\x23\x78\x31\x46\x36\x30\x30\x3b

But when I put the value directly, it prints the correct data:

$emoIcon = "\u{1F600}";

$emoIcon = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $emoIcon);
echo $emoIcon; //output 😀
$hex=bin2hex($emoIcon);
echo $hex;  // output f09f9880
$hexVal=chunk_split($hex,2,"\\x");
var_dump($hexVal);  // output  f0\x9f\x98\x80\x
$result= "\\x" . substr($hexVal,0,-2);
var_dump($result);    // output  \xf0\x9f\x98\x80

Upvotes: 1

Views: 476

Answers (1)

user3942918
user3942918

Reputation: 26405

\u{1F600} is a Unicode escape sequence used in double-quoted strings, it must have a literal value - trying to use "\u{$value}", as you've seen, doesn't work (for a couple reasons, but that doesn't matter so much.)

If you want to start with "1F600" and end up with 😀 use hexdec to turn it into an integer and feed that to IntlChar::chr to encode that code point as UTF-8. E.g.:

$value = "1F600";
echo IntlChar::chr(hexdec($value));

Outputs:

😀

Upvotes: 6

Related Questions