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))); } /**