utf8 - PHP URLDecode / UTF8_Encode字符集问题与特殊字符


utf 8 - PHP URLDecode / UTF8_Encode Character Set Issues with special characters

我正在传递一个磅符号£到一个PHP页面,该页面已被ASP URLEncoded为%C2%A3

问题:

urldecode("%C2%A3") // £
ord(urldecode("%C2%A3")) // get the character number - 194
ord("£") // 163  - somethings gone wrong, they should match

这意味着当我执行utf8_encode(urldecode("%C2%A3"))时,我得到£

然而做utf8_encode("£")我得到£如预期的

我该如何解决这个问题?

我不认为ord()是多字节兼容的。它可能只返回字符串中第一个字符的代码,即Â。在调用ord()之前尝试utf8_decode()字符串,看看是否有帮助。

ord(utf8_decode(urldecode("%C2%A3"))); // This returns 163

如果你尝试

var_dump(urldecode("%C2%A3"));

你会看到

string(2) "£"

,因为这是2字节字符,ord()返回第一个字符的值(194 = Â)

关于urldecode和UTF-8的一些信息可以在urldecode文档的第一个注释中找到。

php.net上关于urlencode()的第一条注释解释了这是为什么,并建议使用下面的代码来纠正:

<?php
function to_utf8( $string ) {
// From http://w3.org/International/questions/qa-forms-utf-8.html
    if ( preg_match('%^(?:
      ['x09'x0A'x0D'x20-'x7E]            # ASCII
    | ['xC2-'xDF]['x80-'xBF]             # non-overlong 2-byte
    | 'xE0['xA0-'xBF]['x80-'xBF]         # excluding overlongs
    | ['xE1-'xEC'xEE'xEF]['x80-'xBF]{2}  # straight 3-byte
    | 'xED['x80-'x9F]['x80-'xBF]         # excluding surrogates
    | 'xF0['x90-'xBF]['x80-'xBF]{2}      # planes 1-3
    | ['xF1-'xF3]['x80-'xBF]{3}          # planes 4-15
    | 'xF4['x80-'x8F]['x80-'xBF]{2}      # plane 16
)*$%xs', $string) ) {
        return $string;
    } else {
        return iconv( 'CP1252', 'UTF-8', $string);
    }
}
?> 

你也应该决定你是否希望你发送到浏览器的最终html是在utf-8或其他编码,否则你将继续有£字符在你的代码