Home > php教程 > php手册 > body text

PHP自动识别字符集并完成转码详解

WBOY
Release: 2016-06-13 11:42:17
Original
961 people have browsed it

因为自己使用字符编码一般的是utf-8编码,但如果对方的博客使用gb2312编码的话,POST过来就会出现乱码(除非对方POST前先转换编码)。在不能保证对方是否一定使用utf-8编码的情况下,自己做一个编码的检查和转换是很有必要的。

写了个函数来完成这个工作,原理很简单,因为gb2312/gbk是中文两字节,这两个字节是有取值范围的,而utf-8中汉字是三字节,同样每个字节也有取值范围。而英文不管在何种编码情况下,都是小于128,只占用一个字节(全角除外)。

如果是文件形式的编码检查,还可以直接check utf-8的BOM信息,关于这方面的东西,大家可以看看TP工具箱的编码转换功能,我在那个AppCodingSwitch类中写了比较详细的注释。

话不多说,直接上函数,这个函数是用来对字符串进行检查和转码的。文件的检查与转码

复制代码 代码如下:


function safeEncoding($string, $outEncoding = 'UTF-8') {
    $encoding = "UTF-8";
    for ($i = 0; $i         if (ord($string{$i})             continue;

        if ((ord($string{$i}) & 224) == 224) {
            //第一个字节判断通过
            $char = $string{++$i};
            if ((ord($char) & 128) == 128) {
                //第二个字节判断通过
                $char = $string{++$i};
                if ((ord($char) & 128) == 128) {
                    $encoding = "UTF-8";
                    break;
                }
            }
        }
        if ((ord($string{$i}) & 192) == 192) {
            //第一个字节判断通过
            $char = $string{++$i};
            if ((ord($char) & 128) == 128) {
                //第二个字节判断通过
                $encoding = "GB2312";
                break;
            }
        }
    }

    if (strtoupper($encoding) == strtoupper($outEncoding))
        return $string;
    else
        returniconv($encoding, $outEncoding, $string);
}


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!