note 37975 added to function.strlen
| From: | dtorop932 at hotmail dot com | Date: | Wed, 03 Dec 2003 19:25:14 +0000 |
| Subject: | note 37975 added to function.strlen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-61350@lists.php.net to get a copy of this message | ||
To follow up on dr-strange's utf8_strlen(), here are two succinct alternate versions. The
first is slower for multibyte UTF-8, faster for single byte UTF-8. The second should be much faster
for all but very brief strings, and can easily live inline in code. Neither validates the UTF-8.
Note that the right solution is to use mb_strlen() from the mbstring module, if one is lucky enough
to have that compiled in...
<?php
// choice 1
function utf8_strlen($str) {
$count = 0;
for ($i = 0; $i < strlen($str); ++$i) {
if ((ord($str[$i]) & 0xC0) != 0x80) {
++$count;
}
}
return $count;
}
// choice 2
function utf8_strlen($str) {
return preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $dummy);
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.strlen.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+37975
Delete -- http://master.php.net/manage/user-notes.php?action=delete+37975&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+37975&report=yes
Search -- http://master.php.net/manage/user-notes.php