How to convert Emoji from Unicode in PHP?

℡╲_俬逩灬. 提交于 2019-11-27 02:35:38

问题


I use this table of Emoji and try this code:

<?php print json_decode('"\u2600"'); // This convert to ☀ (black sun with rays) ?>

If I try to convert this \u1F600 (grinning face) through json_decode, I see this symbol — ὠ0.

Whats wrong? How to get right Emoji?


回答1:


PHP 5

JSON's \u can only handle one UTF-16 code unit at a time, so you need to write the surrogate pair instead. For U+1F600 this is \uD83D\uDE00, which works:

echo json_decode('"\uD83D\uDE00"');
😀

PHP 7

You now no longer need to use json_decode and can just use the \u and the unicode literal:

echo "\u{1F30F}";
🌏



回答2:


In addition to the answer of Tino, I'd like to add code to convert hexadecimal code like 0x1F63C to a unicode symbol in PHP5 with splitting it to a surrogate pair:

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); outputs 😼



来源:https://stackoverflow.com/questions/33547233/how-to-convert-emoji-from-unicode-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!