在php中檢測字串編碼的方法有很多,最常用的就是直接使用mb_detect_encoding函數了,但還有更進階的辦法就是使用字元的ascii值來判斷哦。
例1
| 代碼如下 |
複製代碼 |
function is_utf8($str) { $c=0; $b=0; $bits=0; $len=strlen($str); for($i=0; $i<$len; $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 < 128 || $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) } |
http://www.bkjia.com/PHPjc/632796.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/632796.htmlTechArticle在php中檢測字串編碼的方法有很多,最常用的就是直接使用mb_detect_encoding函數了,但還有更進階的辦法就是使用字元的ascii值來判斷哦。...