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

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

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

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将图片自动缩放成指定大小:autoCropImage,含nginx伪静态

autoCropImage自己一直在用,并且加入了webp格式转换具体说明和介绍如下:autoCropImage - 图片自动缩放程序将图片自动缩放成指定大小,减少图片体积,从而加快下载速度,降低下载...

php array_column函数封装

array_column函数只支持php5.5.0以上版本,所以这里要封装下,这样可以兼容用法if (!function_exists("array_column"))&...

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

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

困扰了很久的PHP跨域问题

其实这个问题一直是不存在的,只是自己因为各种配置吧,导致了这个问题一直没有解决。现在就解决思路提供如下: 需要两步操作一、修改Nignx配置文件一般在宝塔面板伪静态中设置示例代码: locatio...

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

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

发表评论

访客

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