2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > PHP检测字符串是否为UTF8编码的常用方法【PHP】

PHP检测字符串是否为UTF8编码的常用方法【PHP】

时间:2019-01-07 20:44:17

相关推荐

PHP检测字符串是否为UTF8编码的常用方法【PHP】

后端开发|php教程

PHP,检测,字符串,UTF8,编码

后端开发-php教程

本文实例总结了PHP检测字符串是否为UTF8编码的常用方法。分享给大家供大家参考。具体实现方法如下:

悬浮锁机源码下载,vscode底部栏文字颜色,ubuntu取消注释,如何通过tomcat远程,爬虫非法获取,php 生成json数据,seo和自媒体如何合作,手机选号网网站源码,wp 新页面使用模板lzw

检测字符串编码可以有很多种方法,如利用ord获得字符的进制然后进入判断,或利用mb_detect_encoding函数来处理,下面整理了四种常用方法供大家参考。

淘宝源码里面,ubuntu tp5,tomcat 客户端ip,python爬虫文献,女性学php吃力,杭州seo行者seo09lzw

例子1

android 开发框架源码,ubuntu缺失系统字体,tomcat安装设置编码,java爬虫deom,php 统计字符,零基础如何学seo 网销lzw

/**

* 检测字符串是否为UTF8编码

* @param string $str 被检测的字符串

* @return boolean

*/

function is_utf8($str){

$len = strlen($str);

for($i = 0; $i < $len; $i++){

$c = ord($str[$i]);

if ($c > 128) {

if (($c > 247)) return false;

elseif ($c > 239) $bytes = 4;

elseif ($c > 223) $bytes = 3;

elseif ($c > 191) $bytes = 2;

else return false;

if (($i + $bytes) > $len) return false;

while ($bytes > 1) {

$i++;

$b = ord($str[$i]);

if ($b 191) return false;

$bytes--;

}

}

}

return true;

}

例子2

function is_utf8($string) {

return preg_match(\%^(?:

[\x09\x0A\x0D\x20-\x7E] # ASCII

| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte

|\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs

| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}# straight 3-byte

|\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates

|\xF0[\x90-\xBF][\x80-\xBF]{2}# planes 1-3

| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15

|\xF4[\x80-\x8F][\x80-\xBF]{2}# plane 16

)*$%xs, $string);

}

准确率基本和mb_detect_encoding()一样,要对一起对,要错一起错。

编码检测不可能100%准确,这个东西已经可以基本满足要求了。

例子3

function mb_is_utf8($string)

{

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

}

例子4

// Returns true if $string is valid UTF-8 and false otherwise.

function is_utf8($word)

{

if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true)

{

return true;

}

else

{

return false;

}

} // function is_utf8

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。