Home >Backend Development >PHP Tutorial >javascript unescape() escape() character encoding and decoding function_PHP tutorial
The
escape() function encodes a string so that it can be read on all computers.
Grammar
escape(string) parameter description
string required. The string to be escaped or encoded.
Return value
A copy of the encoded string. Some of the characters are replaced with hexadecimal escape sequences
Grammarfunction php tutorial escape($str)
{
$sublen=strlen($str);
$retrunstring="";
for ($i=0;$i<$sublen;$i++)
If(ord($str[$i])>=127)
$ TMPS tutorial tring = bin2hex (iconv ("GB2312", "UCS-2", substr ($ STR, $ i, 2));
// $tstring=substr. $retrunstring.="%u".$tmpstring;
$i++;
} else {
$retrunstring.="%".dechex(ord($str[$i]));
} }
return $retrunstring;
}
The unescape() function decodes a string encoded with escape().
unescape(string) parameter description
string required. The string to decode or unescape.
Return value
A decoded copy of string.
The function works by decoding by finding character sequences of the form %xx and %uxxxx (x represents a hexadecimal number) and replacing such character sequences with the unicode characters u00xx and uxxxx.
$str = rawurldecode($str);
Preg_match_all("/%u.{4}|.{4};|d+;|.+/u",$str,$r);$ar = $r[0];foreach($ar as $k=>$v) {
If(substr($v,0,2) == "%u")
$ar[$k] = iconv("ucs-2","gbk",pack("h4",substr($v,-4)));
elseif(substr($v,0,3) == "")
$ar[$k] = iconv("ucs-2","gbk",pack("h4",substr($v,3,-1)));
elseif(substr($v,0,2) == "") {
$ar[$k] = iconv("ucs-2","gbk",pack("n",substr($v,2,-1)));
}
return join("",$ar);
}