注意:数据库字符集需设置为:utf8mb4
//表情转义---存到数据库中
public function userTextEncode($str)
{
if (!is_string($str)) {
return $str;
}
if (!$str || $str == 'undefined') {
return '';
}
$text = json_encode($str);
$text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($str) {
return addslashes($str[0]);
}, $text);
return json_decode($text);
}
//反解析---从数据库中读取再解析为表情
public function userTextDecode($str)
{
$text = json_encode($str);
$text = preg_replace_callback('/\\\\\\\\/i', function ($str) {
return '\\';
}, $text);
return json_decode($text);
}
用法如下:取出数据时同理,调用userTextDecode方法即可