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;
}