PHP怎么处理emoji表情

PHPz
Release: 2020-09-04 17:13:45
Original
2124 people have browsed it

PHP怎么处理emoji表情

PHP处理emoji表情的方法:

最近项目中用户反映发表文章文字保存不全,经过检查发现是emoji表情造成,在使用MySQL直接存储的时候 没有存进去,查找了发现这个方法,特意记录一下 (直接将emoji表情过滤掉 ; 也有时候需要保留emoji表情 , 那么就只能转义保存 , 取出来的时候 , 再转回来 , 类似于编码和解码!)

1.过滤emoji表情

/** 
 * 过滤特殊字符
 * $str
 **/ 
function filter($str){      
    if($str){ 
        $name = $str; 
        $name = preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $name); 
        $name = preg_replace('/xE0[x80-x9F][x80-xBF]‘.‘|xED[xA0-xBF][x80-xBF]/S','?', $name); 
        $return = @json_decode(preg_replace("#(\\\ud[0-9a-f]{3})#ie","",json_encode($name))); 
    }else{ 
        $return = ''; 
    }     
    return $return; 
}
Copy after login

2.编码解码

function userTextEncode($str){
    if(!is_string($str)) return $str;
    if(!$str || $str=='undefined') return '';
 
    $text = json_encode($str); //暴露出unicode
    $text = preg_replace_callback("/(\\\u[2def][0-9a-f]{3})/i",function($str){
        return addslashes($str[0]);
    },$text); //将emoji的unicode留下,其他不动,这里的正则比原答案增加了d,因为我发现我很多emoji实际上是\ud开头的,反而暂时没发现有\ue开头。
    return json_decode($text);
}
 
function userTextDecode($str){
    $text = json_encode($str); //暴露出unicode
    $text = preg_replace_callback('/\\\\\\\\/i',function($str){
        return '\\';
    },$text); //将两条斜杠变成一条,其他不动
    return json_decode($text);
}
Copy after login

更多相关知识,请访问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