php后台无法保存emoji表情

今天在做微信小程序开发的时候碰上的问题:emoji表情无法保存。

搜索了一下相关问题,发现是数据库是无法保存emoji表情等特殊字符,只有进行编码解码。

弄了个工具类。

<?php
/**
 * Created by PhpStorm.
 * User: 老辉辉
 * Date: 2017/12/18
 * Time: 14:30
 */
namespace app\common\util;

class HtmlUtil
{
    /**
     *把用户输入的文本转义,用于保存
     * (主要针对特殊符号和emoji表情)
     */
    function userTextEncode($str){
        if(!is_string($str))return $str;
        if(!$str || $str=='undefined')return '';

        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
            return addslashes($str[0]);
        },$text); //将emoji的unicode留下,这里的正则比原来增加了d,很多emoji实际上是\ud开头的,反而没发现有\ue开头。
        return json_decode($text);
    }
    /**
     *解码上面的转义,用于显示
     */
    function  userTextDecode($str){
        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback('/\\\\\\\\/i',function($str){
            return '\\';
        },$text); //将两条斜杠变成一条
        return json_decode($text);
    }
}


猜你喜欢

转载自blog.csdn.net/qq_20745827/article/details/78832900
今日推荐