PHP code example for decoding unicode encoded Chinese characters,

Source: Internet
Author: User

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)




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.