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

时间:2015-11-19 08:31:54

标签: php string unicode utf-8 emoji

我有一个字符串,它是表单的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);

2 个答案:

答案 0 :(得分:0)

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

unescape和decode的代码非常简单:

$myInput = '\\ud83d\\ude01';

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

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

答案 1 :(得分:0)

使用:

解决了这个问题
print json_encode('"$emoji"');

发现这是最简单的方法。