当前位置:首页 > 后端

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

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

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()输出错误后,…

【转】rtsp视频流实现浏览器h5播放

【转】rtsp视频流实现浏览器h5播放

方案思路:获取摄像头数据流 --> FFmpeg转码 --> Node.js(搭建webSocket服务器) --> 在服务器上运行jsmpeg程序操作步骤首先查看是否能够正常地获取…

【转】Swoole和Workerman到底选谁?

【转】Swoole和Workerman到底选谁?

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

Composer的初步使用以及Composer切换国内源(阿里云)

Composer安装(Windows系统)下载:https://getcomposer.org/Composer-Setup.exe一步步安装即可。需要注意的是你需要开启 openssl 配置,我们打…

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

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

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

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。