php 如何处理 emoji 表情,保存到 mysql
不考虑数据库的编码格式什么之类的,最直接的方法就是把文本中的 emoji 转换成文本保存。取出的时候再将文本转换成 emoji 表格即可。
直接上代码:
/* * unicode -> text */
function unicodeEncode($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);
}
/** * text -> unicode */
function unicodeDecode($str)
{
$text = json_encode($str);
$text = preg_replace_callback('/\\\\\\\\/i', function ($str) {
return '\\';
}, $text);
return json_decode($text);
}
实例
我有一个日记项目,支持 emoji 后,在取出和保存的时候都会对文本进行处理
保存时:
$title = unicodeEncode($title);
$content = unicodeEncode($content);
取出时:
// 处理数据,把带 emoji 表情的数据解析出来
$decodedDiaries = array();
foreach ($diaries as $diary){
$diary['title'] = unicodeDecode($diary['title']);
$diary['content'] = unicodeDecode($diary['content']);
array_push($decodedDiaries, $diary);
}
$response->setData($decodedDiaries);