5

PHP删除字符串中的emoji表情

 2 years ago
source link: http://pein0119.github.io/2015/09/20/PHP%E5%88%A0%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84emoji%E8%A1%A8%E6%83%85/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PHP删除字符串中的emoji表情

导引:单个emoji字符的长度为4个字节,而我们使用的MySQL数据的编码最长只支持3字节字符,所以插入emoji表情时会报错,最终的解决方案是将MySQL的编码修改为utf8mb4。

最近用户注册时喜欢在昵称中添加emoji表情,经常导致数据库插入查询失败。临时的解决方案是删除字符串中的emoji表情,代码如下:

// 过滤掉emoji表情
function filterEmoji($str)
{
$str = preg_replace_callback(
'/./u',
function (array $match) {
return strlen($match[0]) >= 4 ? '' : $match[0];
},
$str);

return $str;
}

基本思想就是遍历字符串中的每个字符,如果该字符的长度为4个字节,就将其删除。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK