首页 > 解决方案 > 改进识别和转换 Unicode 表情符号的功能

问题描述

我有这个功能来转换标签提及

<?php 

function convertAll($str) {
    $regex = "/[@#](\w+)/";
    //type and links
    $hrefs = [
        '#' => 'hashtag?tag',
        '@' => 'profile?username'
    ];

    $result = preg_replace_callback($regex, function($matches) use ($hrefs) {
         return sprintf(
             '<a href="%s=%s">%s</a>',
             $hrefs[$matches[0][0]],
             $matches[1], 
             $matches[0]
         );
    }, $str);

    return($result);
}

$text = "text example - #php text here @test text here";
//emoji list http://www.unicode.org/emoji/charts/emoji-list.html
//echo "\u{emoj};
//emoji test
echo '<div style="font-size: 100px;">';
echo "\u{1F30F}";
echo '</div>';
//function only
echo convertAll($text);

UNICODE 表情符号http ://www.unicode.org/emoji/charts/emoji-list.html

因此,根据我的 echo Unicode 示例,我需要用 Unicode 字符替换与表情符号对应的 Unicode 代码点。

例如:
我想替换U+1F617\u{1F617}

给定 U+XXXXX 格式的 UNICODE 代码点,我想使用正则表达式将其替换为实际的 UNICODE 字符。我怎么能这样做?

标签: phpregexunicodeemoji

解决方案


您当前的使用preg_replace_callback()假设所有正则表达式匹配都将替换为链接。由于表情符号不会用作链接的一部分,因此最简单的解决方案是保持preg_replace_callback()原样,在我们进行 unicode 替换之后添加一个额外的步骤。

function convertAll($str) {
    $regex = "/[@#](\w+)/";
    //type and links
    $hrefs = [
        '#' => 'hashtag?tag',
        '@' => 'profile?username'
    ];

    $result = preg_replace_callback($regex, function($matches) use ($hrefs) {
         return sprintf(
             '<a href="%s=%s">%s</a>',
             $hrefs[$matches[0][0]],
             $matches[1], 
             $matches[0]
         );
    }, $str);

    $result = preg_replace("/U\+([A-F0-9]{5})/", '\u{${1}}', $result);

    return($result);
}

的正则表达式部分preg_replace()是说要匹配文字“U”,后跟文字“+”,然后是任何字符 AZ 或 0-9 的 5 个实例。我们正在捕获这 5 个字符并将它们放在文字“\u{”之后,然后在它们后面加上文字“}”。

演示

可能有办法在 内部执行此操作preg_replace_callback(),但这似乎比我现在愿意付出的努力要多。如果有人想出一个可以做到这一点的答案,我很乐意看到它。

要替换为 HTML 实体,请preg_replace改用:

$result = preg_replace("/U\+([A-F0-9]{5})/", "&#x\\1;", $result);

推荐阅读