emoji表情处理,emoji表情的编码解码

如题所述

第1个回答  2022-06-05
emoji表情的编码解码

该方法实体编码后内容在页面是可以直接显示的,不需要解码,只有在js中才需要解码,同名的php函数具有相同编码功能

下面这句是js编码方法,直接带入字符串就可以直接复制到项目中使用了

function emoji_encode(e){var n=/[\ud800-\udbff][\udc00-\udfff]/g;return e=e.replace(n,function(e){var n,r;return 2===e.length?(n=e.charCodeAt(0),r=e.charCodeAt(1),"&#"+(1024*(n-55296)+65536+r-56320)+";"):e})}

下面是经过上面编码后,在js环境下乳 uni-app的h5页面中调用,需要调用下面的解码才能正常显示。

function emoji_decode(e){var n=/\&#.*?;/g;return e.replace(n,function(e){var n,r,t;return 9==e.length?(t=parseInt(e.match(/[0-9]+/g)),n=Math.floor((t-65536)/1024)+55296,r=(t-65536)%1024+56320,unescape("%u"+n.toString(16)+"%u"+r.toString(16))):e})}

php环境下的编码通过下面方法调用代入str参数就可以了实现编码了 

function emoji_encode($str){

    preg_match_all('/./u',$str,$matches);

    $unicodeStr = "";

    foreach($matches[0] as $m){

        $unicodeStr .=(strlen($m) >= 4 )?"&#".base_convert(bin2hex(iconv('UTF-8',"UCS-4",$m)),16,10).';':$m;

    }

    return $unicodeStr;

}
相似回答