20090224

php unescape

  javascript escape用php解。差點被這搞死~"~


function unescape ($source) {
$decodedStr = "";
$pos = 0;
$len = strlen ($source);
while ($pos < $len)
{
$charAt = substr ($source, $pos, 1);
if ($charAt == '%') {
$pos++;
$charAt = substr ($source, $pos, 1);
if ($charAt == 'u')
{
$pos++;
$unicodeHexVal = substr ($source, $pos, 4);
$unicode = hexdec ($unicodeHexVal);
$entity = "&#". $unicode . ';';
$decodedStr .= utf8_encode ($entity);
$pos += 4;
}
else
{
$hexVal = substr ($source, $pos, 2);
$decodedStr .= chr (hexdec ($hexVal));
$pos += 2;
}
}
else
{
$decodedStr .= $charAt;
$pos++;
}
}
$decodedStr = mb_convert_encoding($decodedStr,'utf-8', 'HTML-ENTITIES');
return $decodedStr;
}

2 則留言:

vera's Blog 提到...

但遇到big5特殊字還適用嗎
想到之前我也為此很煩惱
後來就放棄了

提到...

把這段拿掉
$decodedStr = mb_convert_encoding($decodedStr,'utf-8', 'HTML-ENTITIES');
應該就適用了
因為所有的字都會變&#xxxxxx;
拿掉那段只是把&#xxxxxx;轉成utf8
至於真的假的,就等妳實驗啦
我手上沒有怪怪的BIG-5字元XD