php 字符编码判断和编码转换

。。。一些原理,自行度娘。。。

我删除了原来的一些废话,就是说,你想检测编码或者转换。看此文。

判断编码方式,一是,开头几字节标记,二是,正则范围。

三是,官方示例,四是,DIY。

下面,简单聊聊:

比如GBK转成UTF-8,

最早,是用:

iconv("gbk","utf-8//IGNORE","乡亲们,把窗户都开开,看看我是谁家的");

遇到“—”一些特别字,会出错,所以用IGNORE标记忽略尴尬。

mbstring模块,有个新同学。

mb_detect_encoding("我是什么编码")

mb_detect_encoding("我是什么编码",优先检测编码顺序)

mb_convert_encoding("我将要被转换", "目标编码比如UTF-8", "原编码或auto");

上面两个功能,我们看看实例:

$oldtext="剧情大反转"; 
//或者
//$oldtext = file_get_contents("test.txt");

$encoding = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1');
$encodType = mb_detect_encoding($oldtext, $encoding);
error_log('转换前:'.$encodType.'\n',3,'errors.log');

$content=mb_convert_encoding($oldtext, "UTF-8", $encodType);
$encodType = mb_detect_encoding($content, $encoding);
error_log('转换后:'.$encodType.'\n',3,'errors.log');

mb_detect_encoding 说实话,官方实例有时并不准确,

看网上一个办法,大力推荐:

$list = array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1');
$str = "统一测试,解放未来";
$encodType="未知";
foreach ($list as $item) {
	$tmp = mb_convert_encoding($str, $item, $item);
	if (md5($tmp) == md5($str)) {
		$encodType=$item;
	}
}

就这样,没有更多的内容。

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注