这似乎可以在大多数浏览器和字符编码配置之间正确解码。特别适合直接解析 URL,因为它会在环境变量中出现。
function crossUrlDecode($source) {
$decodedStr = '';
$pos = 0;
$len = strlen($source);
while ($pos < $len) {
$charAt = substr ($source, $pos, 1);
if ($charAt == '?') {
$char2 = substr($source, $pos, 2);
$decodedStr .= htmlentities(utf8_decode($char2),ENT_QUOTES,'ISO-8859-1');
$pos += 2;
}
elseif(ord($charAt) > 127) {
$decodedStr .= "&#".ord($charAt).";";
$pos++;
}
elseif($charAt == '%') {
$pos++;
$hex2 = substr($source, $pos, 2);
$dechex = chr(hexdec($hex2));
if($dechex == '?') {
$pos += 2;
if(substr($source, $pos, 1) == '%') {
$pos++;
$char2a = chr(hexdec(substr($source, $pos, 2)));
$decodedStr .= htmlentities(utf8_decode($dechex . $char2a),ENT_QUOTES,'ISO-8859-1');
}
else {
$decodedStr .= htmlentities(utf8_decode($dechex));
}
}
else {
$decodedStr .= $dechex;
}
$pos += 2;
}
else {
$decodedStr .= $charAt;
$pos++;
}
}
return $decodedStr;
}