php:PHP自动识别字符集并完成转码
PHP自动识别字符集并完成转码
因为自己使用字符编码一般的是utf-8编码,但如果对方的博客使用gb2312编码的话,POST过来就会出现乱码(除非对方POST前先转换编码)。在不能保证对方是否一定使用utf-8编码的情况下,自己做一个编码的检查和转换是很有必要的。
写了个函数来完成这个工作,原理很简单,因为gb2312/gbk是中文两字节,这两个字节是有取值范围的,而utf-8中汉字是三字节,同样每个字节也有取值范围。而英文不管在何种编码情况下,都是小于128,只占用一个字节(全角除外)。
如果是文件形式的编码检查,还可以直接check utf-8的BOM信息,关于这方面的东西,大家可以看看TP工具箱的编码转换功能,我在那个AppCodingSwitch类中写了比较详细的注释。
话不多说,直接上函数,这个函数是用来对字符串进行检查和转码的。文件的检查与转码
[php]
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);
}

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
