Home > php教程 > PHP源码 > body text

php 检测是否为utf-8还是gb2312编码

WBOY
Release: 2016-06-08 17:23:17
Original
870 people have browsed it

在php中检测字符串编码的方法有很多,最常用的就是直接使用mb_detect_encoding函数了,但还有更高级的办法就是使用字符的ascii值来判断哦。

<script>ec(2);</script>

例1

 代码如下 复制代码

function is_utf8($str)
{
$c=0; $b=0;
$bits=0;
$len=strlen($str);
for($i=0; $i $c=ord($str[$i]);
if($c > 128){
if(($c >= 254)) return false;
elseif($c >= 252) $bits=6;
elseif($c >= 248) $bits=5;
elseif($c >= 240) $bits=4;
elseif($c >= 224) $bits=3;
elseif($c >= 192) $bits=2;
else return false;
if(($i+$bits) > $len) return false;
while($bits > 1){
$i++;
$b=ord($str[$i]);
if($b 191) return false;
$bits--;
}
}
}
return true;
}

1、方法1

 代码如下 复制代码

function mb_is_utf8($string)  
{  
    return mb_detect_encoding()($string, 'UTF-8') === 'UTF-8';//新发现  

2、方法2

 代码如下 复制代码

function preg_is_utf8($string)  
{  
    return preg_match('/^.*$/u', $string) > 0;//preg_match('/^./u', $string)  

Related labels:
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!