This article provides a detailed analysis of the methods for implementing javascript escape and unescape functions using PHP. if you need a friend, refer to the front-end development engineers who know that javascript has an encoding function escape () and the corresponding decoding function unescape (), while php only has urlencode and urldecode. this encoding and decoding function is valid for encodeURI and encodeURIComponent, but is invalid for escape.
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:
The 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:
The code is as follows:
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;
}