How to convert Emoji from Unicode in PHP?

后端 未结 2 2058
南笙
南笙 2020-12-05 23:57

I use this table of Emoji and try this code:


相关标签:
2条回答
  • 2020-12-06 00:19

    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"');
                                                                        
    0 讨论(0)
  • 2020-12-06 00:19

    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

    0 讨论(0)
提交回复
热议问题