How to Use PHP to implement javascript escape and unescape Functions

Source: Internet
Author: User

Front-end developers know that javascript has the encoding function escape () and the corresponding decoding function unescape (), while php only has urlencode and urldecode. This encoding and decoding function is effective for encodeURI and encodeURIComponent, however, escape is invalid.
The escape () function and the unescape () function in javascript are user string encoded. Similar to the urlencode () function in PHP, the following is the escape Function Code implemented by php: Copy codeThe Code is as follows :/**
* Js escape php implementation
* @ Param $ string the sting want to be escaped
* @ Param $ in_encoding
* @ Param $ out_encoding
*/
Function escape ($ 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 code for decoding php unescape is:Copy codeCode: function unescape ($ 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;
}

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.