- 论坛徽章:
- 0
|
- 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;
- }
复制代码
另一段速度要快些,但有时会判断出错。
- function getUTF8str($value_1)
- {
- $value_2 = @iconv("gb18030//IGNORE","utf-8//IGNORE",$value_1);
- $value_3 = @iconv("utf-8//IGNORE","gb18030//IGNORE",$value_2);
- if(strlen($value_1) == strlen($value_3)){
- return $value_2;
- }else{
- return $value_1;
- }
- }
复制代码 |
|