PHP decoding Unicode encoding Chinese character code example

Source: Internet
Author: User

After crawling a Web site data, the results found a string of encoded data in the packet: ".... \u65b0\u6d6a\u5fae\u535a ...", this is actually Chinese Unicode encoded after the data, want to decode the Chinese.
Solution:
Scenario A (Stable + recommended):

functionReplace_unicode_escape_sequence ($match) {returnMb_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 Academy//We will package the above scenario A to wrap up ~ ~ ~ (Plan a stable version + upgrade + recommended)classhelper_tool{Static functionUnicodedecode ($data){ functionReplace_unicode_escape_sequence ($match) {returnMb_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;} }//called$name= ' \u65b0\u6d6a\u5fae\u535a ';$data= Helper_tool::unicodedecode ($name);//output Sina Weibo

Scenario B (Recommended):

<?PHPfunctionUnicodedecode ($name){$json= ' {' str ': '.$name.‘"}‘;$arr= Json_decode ($json,true);if(Empty($arr))return‘‘; return $arr[' Str '];} //www.jbxue.com$name= ' \u65b0\u6d6a\u5fae\u535a ';EchoUnicodedecode ($name);//output: Sina Weibo

For scenario B, note that in the friend XAR (Poke XAR blog) technical support, summed up the string to be processed (that is, the parameters passed to the function Unicodedecode $name must not contain single quotation marks, otherwise it will lead to parsing failure, so if necessary, you can use str The _replace () function formats illegal 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.