PHP转义emoji表情

PHP 转义emoji表情。

使用场景:使用微信登录,保存用户名,当用户名中包含表情时候会报错或者问号。

解决方法:将表情转义,存储到数据库,使用时反转义。

CODE:

function emoji_encode($str){
    $strEncode = '';

    $length = mb_strlen($str,'utf-8');

    for ($i=0; $i < $length; $i++) {
        $_tmpStr = mb_substr($str,$i,1,'utf-8');
        if(strlen($_tmpStr) >= 4){
            $strEncode .= '[[EMOJI:'.rawurlencode($_tmpStr).']]';
        }else{
            $strEncode .= $_tmpStr;
        }
    }

    return $strEncode;
}
//对emoji表情转反义
function emoji_decode($str)
{
    $strDecode = preg_replace_callback('|\[\[EMOJI:(.*?)\]\]|', function ($matches) {
        return rawurldecode($matches[1]);
    }, $str);
    return $strDecode;
}

You May Also Like

About the Author: 萌新

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注