php - 改进识别和转换 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 字符。我怎么能这样做?
解决方案
您当前的使用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);
推荐阅读
- c# - 通过在旧版本 Entity Framework 中工作的 Entity Framework Core 执行 GroupBy 查询时引发 NullReferenceException
- html - BS4:用新标签包装一系列兄弟姐妹
- perl - 使用 if 语句时是否可以匹配 perl 中的部分单词(包括 bash 示例)
- html - 将html文件另存为aspx
- oracle - ORACLE SQL 开发人员中的 GHOST 列 SYS_NC00008$ 错误 ORA 00001
- c# - 无法在 Socket Close 上访问已处理的对象
- fortran - 如何使用 MPI 并行化双循环并在内循环中读取文件?
- sql - SQL Server - 在 where 子句中使用 DATALENGTH 会导致截断错误
- python - Python的流式`TarFile`和`os.pipe()`:存档不完整
- vuejs2 - 数据与多次使用的同一组件共享