note 90486 added to function.strlen
| From: | anto dot justus at gmail dot com | Date: | Fri, 24 Apr 2009 15:14:55 +0000 |
| Subject: | note 90486 added to function.strlen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-153683@lists.php.net to get a copy of this message | ||
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;
}
?>
----
Server IP: 59.162.86.8
Probable Submitter: 119.82.96.18
----
Manual Page -- http://www.php.net/manual/en/function.strlen.php
Edit -- https://master.php.net/note/edit/90486
Del: integrated -- https://master.php.net/note/delete/90486/integrated
Del: useless -- https://master.php.net/note/delete/90486/useless
Del: bad code -- https://master.php.net/note/delete/90486/bad+code
Del: spam -- https://master.php.net/note/delete/90486/spam
Del: non-english -- https://master.php.net/note/delete/90486/non-english
Del: in docs -- https://master.php.net/note/delete/90486/in+docs
Del: other reasons-- https://master.php.net/note/delete/90486
Reject -- https://master.php.net/note/reject/90486
Search -- https://master.php.net/manage/user-notes.php