From 103488a1cd7341234e36f096c8595383e69327b3 Mon Sep 17 00:00:00 2001 From: Anyon Date: Wed, 27 Mar 2019 15:01:49 +0800 Subject: [PATCH] =?UTF-8?q?[=E6=9B=B4=E6=96=B0]Emoji=E8=A1=A8=E6=83=85?= =?UTF-8?q?=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WeChat/Contracts/Tools.php | 67 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 3 deletions(-) diff --git a/WeChat/Contracts/Tools.php b/WeChat/Contracts/Tools.php index fda7e90..d0de000 100644 --- a/WeChat/Contracts/Tools.php +++ b/WeChat/Contracts/Tools.php @@ -160,9 +160,70 @@ class Tools */ public static function arr2json($data) { - return preg_replace_callback('/\\\\u([0-9a-f]{4})/i', function ($matches) { - return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE"); - }, ($json = json_encode($data)) == '[]' ? '{}' : $json); + $json = json_encode(self::buildEnEmojiData($data), JSON_UNESCAPED_UNICODE); + return $json === '[]' ? '{}' : $json; + } + + /** + * 数组对象Emoji编译处理 + * @param array $data + * @return array + */ + public static function buildEnEmojiData(array $data) + { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = self::buildEnEmojiData($value); + } elseif (is_string($value)) { + $data[$key] = self::emojiEncode($value); + } else { + $data[$key] = $value; + } + } + return $data; + } + + /** + * 数组对象Emoji反解析处理 + * @param array $data + * @return array + */ + public static function buildDeEmojiData(array $data) + { + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = self::buildDeEmojiData($value); + } elseif (is_string($value)) { + $data[$key] = self::emojiDecode($value); + } else { + $data[$key] = $value; + } + } + return $data; + } + + /** + * Emoji原形转换为String + * @param string $content + * @return string + */ + public static function emojiEncode($content) + { + return json_decode(preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i", function ($string) { + return addslashes($string[0]); + }, json_encode($content))); + } + + /** + * Emoji字符串转换为原形 + * @param string $content + * @return string + */ + public static function emojiDecode($content) + { + return json_decode(preg_replace_callback('/\\\\\\\\/i', function () { + return '\\'; + }, json_encode($content))); } /**