note 108603 deleted from function.strlen by salathe

From: Date: Thu, 10 May 2012 08:13:59 +0000
Subject: note 108603 deleted from function.strlen by salathe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-187566@lists.php.net to get a copy of this message
Note Submitter: Krinkle ---- 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.

« previous php.notes (#187566) next »