JavaScript PHP 通过URLEncode字串判断其编码是UTF-8还是GBK

时间:2023-01-05 21:22:00

例如给出字串:

    %B4%BA

    %E6%98%A5

如何判断应该是使用UTF-8还是GBK进行URLDecode?

思路1 通用方法:
假定它是 GBK 的编码 ,则将其转换成 utf-8 然后再转换回来后与没有转换之前是相等的。这样假设成立,也就是GBK编码。

思路2
iconv转换编码时 如果转换遇到错误 会抛出异常 扑捉异常即可

    <?php
//测试url编码到底是gbk 还是utf8编码
$url="%B4%BA";
check_type1($url);
check_type2($url);
function check_type1($url){
//这是思路1
$url=urldecode($url);
$temp1
=iconv("GBK","UTF-8",$url);
$temp2
=iconv("UTF-8","GBK",$temp1);
//var_dump($temp1,$temp2);
if($temp2==$url)
echo
'it is gbk';
else
echo
'it is utf8';
}

function check_type2($url){
//这是思路2
$url=urldecode($url);
@trigger_error(
'error', E_USER_NOTICE);
$temp1
=@iconv("GBK","UTF-8",$url);
$error
=error_get_last();
if($error['message']!='error')
echo
"it is utf8";
else
echo
'it is gbk';
}
?>