🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### PHP ``` $emoji = '表情🤣'; $str = emojiEncode($emoji); echo $str; // 表情\ud83e\udd23 echo '<br />'; $str = '表情\ud83e\udd23'; $emoji = emojiDecode($str); echo $emoji; /** * 转码 */ function emojiEncode($str) { if (!is_string($str)) { return $str; } if (!$str || $str == 'undefined') { return ''; } $text = str_replace('\\', '/', $str); $text = json_encode($text); //暴露出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 emojiDecode($str) { if (empty($str)) { return ''; } $str = str_replace('\\', '/', $str); $str = preg_replace_callback('/(\/u[ed][0-9a-f]{3})/i', function ($value) { return str_replace('/', '\\', $value[0]); }, $str); $text = json_encode($str); //暴露出unicode $text = preg_replace_callback('/\\\\\\\\/i', function () { return '\\'; }, $text); //将两条斜杠变成一条,其他不动 $rt = json_decode($text); if ($rt) { return $rt; } return $str; } ``` 输出结果: ![](https://img.kancloud.cn/35/83/3583eb58568c9ece0140f66c334716c2_181x69.png) ### Go ``` package main import ( "fmt" "os" "regexp" "strconv" "strings" "unicode/utf16" ) // EmojiEncode Emoji表情转码 func EmojiEncode(s string) string { ret := "" rs := []rune(s) for i := 0; i < len(rs); i++ { if len(string(rs[i])) == 4 { r1, r2 := utf16.EncodeRune(rs[i]) t1 := "\\u" + fmt.Sprintf("%x", r1) t2 := "\\u" + fmt.Sprintf("%x", r2) ret += t1 + t2 } else { ret += string(rs[i]) } } return ret } // EmojiDecode Emoji表情解码 func EmojiDecode(s string) string { re := regexp.MustCompile("\\\\u[ed][0-9a-f]{3}\\\\u[ed][0-9a-f]{3}") result := re.FindAllString(s, -1) if len(result) > 0 { for k := range result { tmp := result[k] result[k] = strings.Replace(result[k], "\\u", "0x", -1) cov1, _ := strconv.ParseUint(result[k][:6], 0, 32) cov2, _ := strconv.ParseUint(result[k][6:], 0, 32) covResult := fmt.Sprintf("%c", utf16.DecodeRune(rune(cov1), rune(cov2))) s = strings.Replace(s, tmp, covResult, -1) } } return s } func main() { /* // emoji表情转码 emoji := os.Args[1] str := EmojiEncode(emoji) fmt.Println(str) */ // 字符串解码 str := os.Args[1] emoji := EmojiDecode(str) fmt.Println(emoji) } ``` 输出结果: ![](https://img.kancloud.cn/f5/1f/f51f80f504d7d75eb1acfdac26dd6321_365x86.png)