如何在 PHP 中从 Unicode 转换表情符号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33547233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:32:18  来源:igfitidea点击:

How to convert Emoji from Unicode in PHP?

phpunicodeemoji

提问by Platon

I use this table of Emojiand 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.

如果我尝试通过 转换这个\u1F600(咧嘴笑的脸)json_decode,我会看到这个符号 — ?0

Whats wrong? How to get right Emoji?

怎么了?如何获得正确的表情符号?

回答by Tino Didriksen

PHP 5

PHP 5

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

JSON\u一次只能处理一个 UTF-16 代码单元,因此您需要编写代理对。对于U+1F600这是\uD83D\uDE00,它的工作原理:

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

PHP 7

PHP 7

You now no longer need to use json_decodeand can just use the \uand the unicode literal:

您现在不再需要使用json_decode并且可以只使用\u和 unicode 文字:

echo "\u{1F30F}";

回答by shukshin.ivan

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

除了 Tino 的回答之外,我想添加代码以将十六进制代码转换0x1F63CPHP5 中的 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);outputs

echo codeToSymbol(0x1F63C);产出