Home > Backend Development > PHP Tutorial > php 实现emoji遇到的棘手问题,很棘手!

php 实现emoji遇到的棘手问题,很棘手!

WBOY
Release: 2016-06-06 20:29:02
Original
1260 people have browsed it

<code>function str_emoji($dir,$str){
  if($dir){
    $str=json_encode($str);
    $str=preg_replace('#(\\\ud[0-9a-f]{3}|\\\u2(6|7)[0-9a-f]{2})#ie','addslashes("\\1")',$str);
    //emoji 5.0后,一个表情由两个字符组成
    $str=json_decode($str);
  }else{
    $str=preg_replace('#(u[0-9a-f]{4}u[0-9a-f]{4})#ie','iconv("UCS-2","UTF-8",pack("H4","\\1"))',$str);
    //此正则匹配ue415ue415形式的数据
    //不能将二进制转成\xf0\x9f\x98\x83形式的UTF-8
  }
  return $str;
};</code>
Copy after login
Copy after login
<code>//写进数据库
$content=str_emoji(true,$content);</code>
Copy after login
Copy after login
<code>//读取数据库
$content=str_emoji(false,$content);</code>
Copy after login
Copy after login

下面问题来了。

iconv("UCS-2","UTF-8",pack("H4","\\1")) 不能将二进制专程UTF-8,怎么破????
另:数据库版本不能直接存储emoji,升级数据库是肯定不可行的方案。

参考文章:http://blog.mc-zone.me/article/322

回复内容:

<code>function str_emoji($dir,$str){
  if($dir){
    $str=json_encode($str);
    $str=preg_replace('#(\\\ud[0-9a-f]{3}|\\\u2(6|7)[0-9a-f]{2})#ie','addslashes("\\1")',$str);
    //emoji 5.0后,一个表情由两个字符组成
    $str=json_decode($str);
  }else{
    $str=preg_replace('#(u[0-9a-f]{4}u[0-9a-f]{4})#ie','iconv("UCS-2","UTF-8",pack("H4","\\1"))',$str);
    //此正则匹配ue415ue415形式的数据
    //不能将二进制转成\xf0\x9f\x98\x83形式的UTF-8
  }
  return $str;
};</code>
Copy after login
Copy after login
<code>//写进数据库
$content=str_emoji(true,$content);</code>
Copy after login
Copy after login
<code>//读取数据库
$content=str_emoji(false,$content);</code>
Copy after login
Copy after login

下面问题来了。

iconv("UCS-2","UTF-8",pack("H4","\\1")) 不能将二进制专程UTF-8,怎么破????
另:数据库版本不能直接存储emoji,升级数据库是肯定不可行的方案。

参考文章:http://blog.mc-zone.me/article/322

存数据库的时候 base_encode64() 取得的时候base_decode64()

mysql编码选择utf8mb4即可

数据库是mysql吧,把数据库和字段编码设置为utf8mb4,可以直接保存表情字符

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template