【问题标题】:PHP keep emoji in unicode but also keep text as plain textPHP 将表情符号保留为 unicode,但也将文本保留为纯文本
【发布时间】:2019-12-18 15:02:38
【问题描述】:

我有这个功能可以将表情符号转换为 unicode,但它也可以将文本转换为十六进制。

如何只转换表情符号并将文本保留为纯文本字符串?

function emoji_to_unicode($emoji) {
   $emoji = mb_convert_encoding($emoji, 'UTF-32', 'UTF-8');
   $unicode = strtoupper(preg_replace("/^[0]{3}/","U+",bin2hex($emoji)));
   return $unicode;
}

$var = ("????x????text here");
$out = '';
for ($i = 0; $i < mb_strlen($var); $i++) {
    $out .= emoji_to_unicode(mb_substr($var, $i, 1));
}
echo "$out\n";

所以

$var = ("????x????text here");

返回给我:

U+1F600U+00078U+1F600U+00074U+00065U+00078U+00074U+00020U+00068U+00065U+00072U+00065

但我需要这样返回:

U+1F600xU+1F600text here

我需要将文本保留为纯文本,但也要将表情符号保留为 unicode 格式。

【问题讨论】:

    标签: php function unicode emoji bin2hex


    【解决方案1】:

    Intl 扩展提供了使用 unicode codepointsblocks 的函数,可让您确定当前字符是否为表情符号。

    function emoji_to_unicode($emoji) {
       $emoji = mb_convert_encoding($emoji, 'UTF-32', 'UTF-8');
       $unicode = strtoupper(preg_replace("/^[0]{3}/","U+",bin2hex($emoji)));
       return $unicode;
    }
    
    $var = ("?x?text here");
    $out = '';
    for ($i = 0; $i < mb_strlen($var); $i++) {
        $char = mb_substr($var, $i, 1);
        $isEmoji = IntlChar::getBlockCode(IntlChar::ord($char)) == IntlChar::BLOCK_CODE_EMOTICONS;
        $out .= $isEmoji ? emoji_to_unicode($char) : $char;
    }
    
    echo $out;
    

    这是predefined constants 的列表,您可以在其中找到所有块。

    【讨论】:

    • 你知道是否可以启用IntlCharvia iniset
    • @OtávioBarreto Intl 是一个 php 扩展,它必须被安装和加载,所以不,不可能与 ini_set 做。
    猜你喜欢
    • 2019-07-31
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2016-06-06
    • 2019-12-11
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    相关资源
    最近更新 更多