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
My Answer:
It seems like the issue is with how you are converting the dynamic Unicode value to UTF-8 code. You can use the `json_encode` function to properly convert the Unicode value to UTF-8 code. Here's an updated version of your code:
php
$value = "1F600";
$emoIcon = json_decode('"\u' . $value . '"');
$emoIcon = preg_replace("/\\\\u([0-9A-F]{2,5})/i", "&#x$1;", $emoIcon);
echo $emoIcon; //output ????
$utf8Code = utf8_encode($emoIcon);
$hex = bin2hex($utf8Code);
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
This should now correctly convert the dynamic Unicode value to UTF-8 code.
Rate this post
3 of 5 based on 4190 votesComments