note 85293 modified in function.utf8-encode by danbrown
| From: | danbrown@php.net | Date: | Thu, 09 Jul 2009 15:25:36 +0000 |
| Subject: | note 85293 modified in function.utf8-encode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158115@lists.php.net to get a copy of this message | ||
Here's my is_utf8 function, to detect valid UTF-8 text.
<?php
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;
}
?>
[NOTE BY danbrown AT php DOT net: Contains a bugfix supplied by "svenmika" on 09-JUL-09
with the following note: "A value of exactly 128 (binary 10000000) in the first byte of a
character is invalid."]
--was--
Here's my is_utf8 function, to detect valid UTF-8 text.
<?php
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;
}
?>
http://php.net/manual/en/function.utf8-encode.php