Using PHP to implement the escape and unescape functions of JavaScript

Source: Internet
Author: User
Tags urlencode

JavaScript has the encoding function escape () and the corresponding decoding function unescape (), while PHP has only one urlencode and UrlDecode, and this encoding and decoding function is valid for encodeURI and encodeURIComponent , but is not valid for escape.
The Escape () function and the unescape () function in JavaScript are encoded in the user string, similar to the UrlEncode () function in PHP, which is the escape function code implemented by PHP:

/** JS escape PHP Implementation * @param $string the string want to be escaped * @param $in _encoding * @param $out _enco Ding*/ functionEscape$string,$in _encoding= ' UTF-8 ',$out _encoding= ' UCS-2 ') {     $return= ' '; if(function_exists(' Mb_get_info ')) {          for($x= 0;$x< Mb_strlen ($string,$in _encoding);$x++) {             $str= Mb_substr ($string,$x, 1,$in _encoding ); if(strlen($str) > 1) {//multi-byte characters                $return. = '%u '.Strtoupper(Bin2Hex(Mb_convert_encoding ($str,$out _encoding,$in _encoding ) ) ); } Else {                 $return. = '% '.Strtoupper(Bin2Hex($str ) ); }         }     }     return $return; }

The corresponding decoding PHP unescape code is:

functionUnescape ($str) {     $ret= ' '; $len=strlen($str);  for($i= 0;$i<$len;$i++)     {         if($str[$i] = = '% ' &&$str[$i+ 1] = = ' U ')         {             $val=Hexdec(substr($str,$i+ 2, 4)); if($val< 0x7f)                 $ret.=CHR($val); Else                  if($val< 0x800)                     $ret.=CHR(0xc0 | ($val>> 6)).CHR(0x80 | ($val& 0x3f)); Else                     $ret.=CHR(0xe0 | ($val>> 12)).CHR(0x80 | (($val>> 6) & 0x3f).CHR(0x80 | ($val& 0x3f)); $i+ = 5; } Else              if($str[$i] = = '% ')             {                 $ret.=UrlDecode(substr($str,$i, 3)); $i+ = 2; } Else                 $ret.=$str[$i]; }     return $ret; }

Using PHP to implement the escape and unescape functions of JavaScript

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.