PHP 5
JSON的\u
一次只能处理一个UTF-16代码单元,因此您需要编写代理对。 对于U+1F600
,这是\uD83D\uDE00
,可以正常工作:
echo json_decode('"\uD83D\uDE00"');
PHP 7
现在您不再需要使用json_decode
函数,只需使用\u
和Unicode字面量即可:
echo "\u{1F30F}";
除了Tino的答案之外,我想添加代码来将类似于0x1F63C
的十六进制代码转换为在PHP5中拆分成代理对的unicode符号:
function codeToSymbol($em) {
if($em > 0x10000) {
$first = (($em - 0x10000) >> 10) + 0xD800;
$second = (($em - 0x10000) % 0x400) + 0xDC00;
return json_decode('"' . sprintf("\\u%X\\u%X", $first, $second) . '"');
} else {
return json_decode('"' . sprintf("\\u%X", $em) . '"');
}
}
echo codeToSymbol(0x1F63C);
的输出结果为
解析包含表情符号Unicode格式的字符串代码示例
$str = 'Test emoji \U0001F607 \U0001F63C';
echo preg_replace_callback(
'/\\\U([A-F0-9]+)/',
function ($matches) {
return mb_convert_encoding(hex2bin($matches[1]), 'UTF-8', 'UTF-32');
},
$str
);
输出:测试表情符号
print('');
。 - roelandutfbm4
。请参阅此处。 - Juan Antonio