note 108603 added to function.strlen
| From: | Krinkle | Date: | Wed, 09 May 2012 21:53:06 +0000 |
| Subject: | note 108603 added to function.strlen | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-187559@lists.php.net to get a copy of this message | ||
Contrary to what some users may think, strlen() does in fact take multi-byte characters into account
and counts them as characters.
Meaning, a strlen() on a string with 1 character of 3 bytes will return 3!
And some of the methods described below in the comments that intend to give a way to count the
bytes, actually fail at doing so.
Test!
<?php
$stuff = array(
'simple' => 'a', // 1 byte
'dollar' => '$', // 1 byte
'cent' => '¢', // 2 bytes
'euro' => 'â¬', // 3 bytes
);
$strlen = array_map('strlen', $stuff);
// Some methods described in comments on php.net/strlen
// Supposedly to count the bytes instead of characters:
$strlen_utf8_decode = array_map('strlen', array_map('utf8_decode', $stuff));
$custom_utf8_strlen = array_map('custom_utf8_strlen', $stuff);
var_dump(array(
'strlen' => $strlen,
'strlen_utf8_decode' => $strlen_utf8_decode,
'custom_utf8_strlen' => $custom_utf8_strlen,
));
function custom_utf8_strlen($s) {
$c = strlen($s); $l = 0;
for ($i = 0; $i < $c; ++$i) if ((ord($s[$i]) & 0xC0) != 0x80) ++$l;
return $l;
}
?>
Output:
array(3) {
["strlen"]=>
array(4) {
["simple"]=>
int(1)
["dollar"]=>
int(1)
["cent"]=>
int(2)
["euro"]=>
int(3)
}
["strlen_utf8_decode"]=>
array(4) {
["simple"]=>
int(1)
["dollar"]=>
int(1)
["cent"]=>
int(1)
["euro"]=>
int(1)
}
["utf8_strlen"]=>
array(4) {
["simple"]=>
int(1)
["dollar"]=>
int(1)
["cent"]=>
int(1)
["euro"]=>
int(1)
}
}
Codpad: http://codepad.org/coJFnTeB
The last examples actually fail at counting the bytes, and a plain strlen() does it perfectly fine.
----
Server IP: 91.199.167.223
Probable Submitter: 82.74.194.195
----
Manual Page -- http://www.php.net/manual/en/function.strlen.php
Edit -- https://master.php.net/note/edit/108603
Del: integrated -- https://master.php.net/note/delete/108603/integrated
Del: useless -- https://master.php.net/note/delete/108603/useless
Del: bad code -- https://master.php.net/note/delete/108603/bad+code
Del: spam -- https://master.php.net/note/delete/108603/spam
Del: non-english -- https://master.php.net/note/delete/108603/non-english
Del: in docs -- https://master.php.net/note/delete/108603/in+docs
Del: other reasons-- https://master.php.net/note/delete/108603
Reject -- https://master.php.net/note/reject/108603
Search -- https://master.php.net/manage/user-notes.php