note 25715 deleted from function.strlen by hholzgra
| From: | hholzgra@php.net | Date: | Thu, 02 Aug 2012 12:11:04 +0000 |
| Subject: | note 25715 deleted from function.strlen by hholzgra | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189606@lists.php.net to get a copy of this message | ||
Note Submitter: dr - strange at shaw dot ca
----
It seems to me that all strings in PHP are ASCII, this is fine for some but for me I need more. I
thought I would show off a small function that I made that will tell you the length of a UTF-8
string. This comes in handy if you want to restrict the size of user input to say 30 chars - but
don't want to force ascii only input on your users.
<?php
function utf8_strlen($str)
{
$count = 0;
for($i = 0; $i < strlen($str); $i++)
{
$value = ord($str[$i]);
if($value > 127)
{
if($value >= 192 && $value <= 223)
$i++;
elseif($value >= 224 && $value <= 239)
$i = $i + 2;
elseif($value >= 240 && $value <= 247)
$i = $i + 3;
else
die('Not a UTF-8 compatible string');
}
$count++;
}
return $count;
}
?>