如何在 PHP 中将表情符号 unicode 字节字符串转换为适当的 UTF-8

How to translate emoji unicode bytes string to appropriate UTF-8 in PHP

我有一个字符串,它是以下形式的 unicode 表示形式:'\ud83d\ude01'。我怎样才能将它翻译成它实际的 UTF-8 表示:''?

我试过以下代码:

$emoji = '\ud83d\ude01';

#Cleanup
$emoji = str_replace("\u", "", $emoji);

#Split hex
$hex_bytes = str_split($emoji, 2);
$hex_bytes_numbers = array();

#Convert to actual numbers
foreach($hex_bytes as $hex)
    array_push($hex_bytes_numbers, hexdec($hex));


$clean_hex_string = implode(array_map("chr", $hex_bytes_numbers));

#Returns: Ø=Þ
echo $clean_hex_string . "\n";

#Returns : ?=?
echo utf8_decode($clean_hex_string);

\ud83d\ude01 看起来是 UTF-16 的转义形式。

反转码和解码的代码很简单:

$myInput = '\ud83d\ude01';

$myHexString = str_replace('\u', '', $myInput);
$myBinString = hex2bin($myHexString);

print iconv("UTF-16BE", "UTF-8", $myBinString);

通过使用解决了它:

print json_encode('"$emoji"');

发现这是最简单的方法。