关于微信表情(emoji表情)入Mysql的解决方案(PHP版)
emoji是4个字节存储,而utf8_general_ci最大支持3字节,解决方案有两个:
1、mysql库的由utf8改成utf8mb4;
2、使用出入库编码转换,比如:base64编码、urlencode编码等,但是base64编码和urlencode编码会大幅度增加字符长度。
因此使用使用json转码,转为unicode,而且只将emoji表情转换为unicode,整理了两个函数如下:
PHP5.2版本(php5.2不支持preg_replace_callback)
/**
* 把用户输入的文本转义
* @author Joe<joe@xcwl.com>
* @version v1.01
* @since 20170205
* @param string $str 传入数据
* @param string $indb r|w,读写
* @return string
*/
function emoji_encode($str, $indb = "r") {
$text = dfstr($str);
if (!$text)
return "";
if ($indb == "r") {
$text = json_encode($text);
$text = preg_replace("/\\\\\\\\/i", "\\", $text);
$text = json_decode($text);
} else {
$text = json_encode($text);
$text = preg_replace("/(\\\u[ed][0-9a-f]{3})/i", "\\\\\\1", $text);
$text = json_decode($text);
}
return $text;
}PHP5.3版本
/**
* 把用户输入的文本转义
* @author Joe<joe@xcwl.com>
* @version v1.01
* @since 20170205
* @param string $str 传入数据
* @param string $indb r|w,读写
* @return string
*/
function emoji_encode($str, $indb = "r") {
$text = dfstr($str);
if (!$text)
return "";
if ($indb == "r") {
$text = json_encode($text);
$text = preg_replace_callback('/\\\\\\\\/i', function($str) {
return '\\';
}, $text);
$text = json_decode($text);
} else {
$text = json_encode($text);
$text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function($str) {
return addslashes($str[0]);
}, $text);
$text = json_decode($text);
}
return $text;
}
