当前位置:首页 > 后端 > 正文内容

关于微信表情(emoji表情)入Mysql的解决方案(PHP版)

Z先生9年前 (2017-02-05)后端4129

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;
}


分享给朋友:

相关文章

php json_decode转换为null的问题解决

在做某一程序的时候,前台组装的json数组,为了能传到后台,使用JSON.stringify将其转换成字符串后后端接收。但是接收后,死活转换不了数组,使用json_last_error()输出错误后,...

php获取文件mime的方法,相对完整,并且已经测试

已经经过测试也相对完整,优先自带类和方法,如果自带类或者方法没有开启的情况下,通过文件扩展名实现,文件扩展名关联了176种如果实在没有开启相关组件也没有匹配到,那么就返回:application/oc...

【转】Swoole和Workerman到底选谁?

【转】Swoole和Workerman到底选谁?

Swoole:面向生产环境的 PHP 异步网络通信引擎       使 PHP 开发人员可以编写高性能的异步并发 TCP、UDP、Unix Socket、HTT...

thinkphp6模型中联合主键、中间表调用的写法

前言Thinkphp框架是不错,但是一些特殊用法几乎找不到文档。模型就新手来说感觉会很麻烦,但是实际上习惯之后会很方便,比如入库和出库的自动格式化,再比如安全的入库。而且模型会让你养成良好的开发习惯,...

ThinkPHP6多应用下配置短路由 - TP6路由

ThinkPHP6多应用下配置短路由 - TP6路由

需要实现的效果:http://xx.com/u/RkdJ80 => http://xx.com/home/url/url/index实现步骤1. 设置tp6隐藏网址的index...

Composer常见故障处理

Segmentation fault (core dumped)错误错误详情Composer在自升级和安装包时均报:Segmentation fault (core dumped)错误 检查分析运行...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。
请先 登录 再评论,若不是会员请先 注册