PHP code example for decoding unicode encoded Chinese characters,
After capturing the data of a website, a series of encoded data is found in the data packet :"...... \ u65b0 \ u6d6a \ u5fae \ u535a ...... ", this is actually the data after the Chinese character is unicode encoded and you want to decode the Chinese character.
Solution:
Solution A (stable version + recommended ):
Function replace_unicode_escape_sequence ($ match) {return mb_convert_encoding (pack ('H * ', $ match [1]), 'utf-8', 'ucs-2be ');} $ name = '\ u65b0 \ u6d6a \ u5fae \ u535a'; $ str = preg_replace_callback ('/\\\ u ([0-9a-f] {4})/I ', 'replace _ unicode_escape_sequence ', $ name); echo $ str; // output: Sina Weibo // www.jbxue.com script school // encapsulate solution ~~~ (Solution A stable version + upgrade + recommended) class Helper_Tool {static function unicodeDecode ($ data) {function replace_unicode_escape_sequence ($ match) {return mb_convert_encoding (pack ('H *', $ match [1]), 'utf-8', 'ucs-2be ');} $ rs = preg_replace_callback ('// \\\ u ([0-9a-f] {4})/I', 'replace _ unicode_escape_sequence ', $ data); return $ rs ;}} // call $ name = '\ u65b0 \ u6d6a \ u5fae \ u535a'; $ data = Helper_Tool: unicodeDecode ($ name); // output Sina Weibo
TIPS: it is helpful to go over the php tutorials abroad.
Solution B (recommended ):
<? Phpfunction unicodeDecode ($ name) {$ json = '{"str ":"'. $ name. '"}'; $ arr = json_decode ($ json, true); if (empty ($ arr) return''; return $ arr ['str'];} // www.jbxue.com $ name = '\ u65b0 \ u6d6a \ u5fae \ u535a'; echo unicodeDecode ($ name); // output: Sina Weibo
For solution B, note that, with the technical support of friend XAR, summarize the string to be processed (that is, the $ name parameter passed to the unicodeDecode function must not contain single quotation marks; otherwise, the parsing will fail. If necessary, use str_replace () function Format invalid characters as qualified characters)