原理:
使用 mb_detect_encoding() 函数来判断字符串是什么编码的。
注意:要把php.ini中 extension=php_mbstring.dll 前的;号去掉,重启apache就可以了。
我创建三个文件:text1.txt text2.txt text3.txt
分别以ASCII UTF-8 UNICODE 的编码方式保存
代码如下:
<?php
define ('UTF32_BIG_ENDIAN_BOM' , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF));
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00));
define ('UTF16_BIG_ENDIAN_BOM' , chr(0xFE) . chr(0xFF));
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE));
define ('UTF8_BOM' , chr(0xEF) . chr(0xBB) . chr(0xBF));
function detect_utf_encoding($text) {
$first2 = substr($text, 0, 2);
$first3 = substr($text, 0, 3);
$first4 = substr($text, 0, 3);
if ($first3 == UTF8_BOM) return 'UTF-8';
elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE';
elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE';
elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE';
elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE';
}
function getFileEncoding($str){
$encoding=mb_detect_encoding($str);
if(empty($encoding)){
$encoding=detect_utf_encoding($str);
}
return $encoding;
}
$file = 'text1.txt';
echo getFileEncoding(file_get_contents($file)); // 输出ASCII
echo '<br />';
$file = 'text2.txt';
echo getFileEncoding(file_get_contents($file)); // 输出UTF-8
echo '<br />';
$file = 'text3.txt';
echo getFileEncoding(file_get_contents($file)); // 输出UTF-16LE
echo '<br />';
?>
分享到:
相关推荐
当在php中使用mb_detect_encoding函数进行编码识别时,很多人都碰到过识别编码有误的问题,例如对与GB2312和UTF- 8,或者UTF-8和GBK(这里主要是对于cp936的判断),网上说是由于字符短是,mb_detect_encoding会出现...
主要介绍了详解PHP中的mb_detect_encoding函数使用方法,包括对字符串编码的转换和判断以及Call to undefined function mb_detect_encoding()错误的解决,需要的朋友可以参考下
给一个字符串,怎么判断它是什么编码呢?php有一个函数:mb_detect_encoding。不过这个东西需要有mb_string库,不是到处都能用的。
Log4j漏洞检测工具,Log4j2_detect工具使用说明,使用详情:https://github.com/webraybtl/Log4j
ssd_detect.pyssd_detect.pyssd_detect.pyssd_detect.pyssd_detect.py
根据不同的浏览器显示不同的首页面,php源码,wap,1、打开根目录 index.php 在 define('SCR','index'); 下面加入 include('sstn/mobile_device_detect.php'); mobile_device_detect(false,true,true,'m/...
复制代码 代码如下:mb_detect_encoding(‘软件开发网’); 可是 mb_detect_encoding 存在一个硬伤,经常出现判断不准确的情况。或许这样就可以解决: 复制代码 代码如下:// 使用 iconv 转换并判断是否等值,效率不高...
C#编程 系统及注册表操作 CPU_Detect(源码)(源码)C#编程 系统及注册表操作 CPU_Detect(源码)(源码)C#编程 系统及注册表操作 CPU_Detect(源码)(源码)C#编程 系统及注册表操作 CPU_Detect(源码)(源码)C#编程 系统及...
edge_detect_moore and mealy
如果不清楚字符串的编码格式的话,就可以将这段字符这样检查:$encode = mb_detect_encoding($string, array(“ASCII”,’UTF-8′,”GB2312′,”GBK”,’BIG5′)); echo $encode;这样就能知道它是什么编码的了。后续...
machine learning - face detect. matlab code
百度人脸采集所需的工具包
mb_convert_encoding这个函数是用来转换编码的。原来一直对程序编码这一概念不理解,不过现在好像有点开窍了。不过英文一般不会存在编码问题,只有中文数据才会有这个问题。比如你用Zend Studio或Editplus写程序时,...
资源来自pypi官网。 资源全名:alibi_detect-0.6.0-py3-none-any.whl
ssd_detect.ipynb可用版,可用于ssd下检测单张图片,放在example/之下