改进识别和转换 unicode 表情符号的功能

Improve function to recognize and convert unicode emojis

我有这个功能可以转换 hashtagmentions.

<?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 字符。我该怎么做?

您当前对 preg_replace_callback() 的使用假设所有正则表达式匹配都将替换为 link。由于表情符号不会用作 link 的一部分,简单的解决方案是保持 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{}', $result);

    return($result);
}

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

DEMO

preg_replace_callback() 内可能有一种方法可以做到这一点,但这似乎比我现在愿意付出的努力要多一些。如果有人想出这样的答案,我很乐意看到它。

要用 HTML 实体替换,请改用此 preg_replace

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