The front-end development engineers know that JavaScript has the encoding function escape () and the corresponding decoding function unescape (), while PHP has only a urlencode and UrlDecode, This encoding and decoding function is valid for encodeURI and encodeURIComponent, but is not valid for escape.
The Escape () function in JavaScript and the unescape () function user string code, similar to the UrlEncode () function in PHP, below is the escape function code implemented by PHP:
Copy Code code 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) {//multibyte character
$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:
Copy Code code 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;
}