Home > Backend Development > PHP Tutorial > php emoji expression processing

php emoji expression processing

WBOY
Release: 2016-07-29 09:02:30
Original
1387 people have browsed it

背景

移动设备经常会发生用户发送的内容中包含emoji表情,未经处理,在显示时就是乱码。

解决方案

1.数据库支持:将Mysql的编码从utf8转换成utf8mb4。 

2.匹配出内容中的emoji表情做过滤或替换

/**
 * 表情转换  更新到ios9.2涵盖编码范围
 * @param $str
 * @return mixed
 */
public static function emoji_to_html($str) {
    $regex = '/([0-9|#][\x{20E3}])|[\x{00ae}|\x{00a9}|\x{203C}|\x{2047}|\x{2048}|\x{2049}|\x{3030}|\x{303D}|\x{2139}|\x{2122}|\x{3297}|\x{3299}][\x{FE00}-\x{FEFF}]?|[\x{2190}-\x{21FF}][\x{FE00}-\x{FEFF}]?|[\x{2300}-\x{23FF}][\x{FE00}-\x{FEFF}]?|[\x{2460}-\x{24FF}][\x{FE00}-\x{FEFF}]?|[\x{25A0}-\x{25FF}][\x{FE00}-\x{FEFF}]?|[\x{2600}-\x{27BF}][\x{FE00}-\x{FEFF}]?|[\x{2900}-\x{297F}][\x{FE00}-\x{FEFF}]?|[\x{2B00}-\x{2BF0}][\x{FE00}-\x{FEFF}]?|[\x{1F000}-\x{1F6FF}][\x{FE00}-\x{FEFF}]?|[\x{1F900}-\x{1F9FF}][\x{FE00}-\x{FEFF}]?/u';
    $str = preg_replace_callback($regex,function($matches){
        $str = json_encode($matches[0]);
        $str = '<em data-emoji=&#39; . str_replace(&#39;\u&#39;, &#39;em:&#39;, $str) . &#39;></em>';
        return $str;
    },$str);
    return $str;
}
从数据库取出后再转回
$string = preg_replace_callback('/<em data-emoji=\"(.*?)\"><\/em>/is', "self::preg_emoji", $string);
/**
 * 输出emoji表情
 * @param $matches
 * @return mixed
 */
public static function preg_emoji($matches)
{
    $str = $matches[0];
    $str = str_replace('em:', '\u', $str);
    return $str;
}
Copy after login
3.直接过滤掉
/**
 * 过滤表情
 * @param $str
 * @return mixed
 */
public static function filter_emoji($str) {
    $regex = '/(\\\u[ed][0-9a-f]{3})/i';
    $str = json_encode($str);
    $str = preg_replace($regex, '', $str);
    return json_decode($str);
}
Copy after login

以上就介绍了php emoji表情处理,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template