Skip to content

Instantly share code, notes, and snippets.

@Jason-cqtan
Last active June 4, 2020 06:47
Show Gist options
  • Save Jason-cqtan/4b3ccb7a5007aab10a05c4d4edb22fb3 to your computer and use it in GitHub Desktop.
Save Jason-cqtan/4b3ccb7a5007aab10a05c4d4edb22fb3 to your computer and use it in GitHub Desktop.
编码、解码文本中带有的emoji
<?php
/**
* 编码
*/
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);
}
//其他参考base_encode64 urlencode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment