golang处理emoji表情转码解码
关于golang项目保存emoji表情对utf8格式的数据库会失败,可以先对表情转码存入,然后取值在解码输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| // 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 }
|