php中处理emoji符号
来源:php教程
作者:
2020-06-21
数据库表是utf8编码的, 所以在存储emoji符号的时候,直接报错,可使用以下方法:
http://stackoverflow.com/questions/12807176/php-writing-a-simple-removeemoji-function#
有时候这种方法不行,可以使用以下方法
/** 把用户输入的文本转义(主要针对特殊符号和emoji表情) */ function userTextEncode($str){ if(!is_string($str))return $str; if(!$str || $str=='undefined')return ''; $text = json_encode($str); //暴露出unicode $text = preg_replace_callback("/(///u[ed][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); }
当然你也可以直接将emoji之类的字符直接过滤掉,存储到数据库中。只需要将 "return addslashes($str[0]); “修改为 reuturn ''即可.
参考:https://segmentfault.com/q/1010000003711491