note 58282 deleted from function.strlen by dave
| From: | dave@php.net | Date: | Fri, 05 May 2006 03:27:16 +0000 |
| Subject: | note 58282 deleted from function.strlen by dave | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-110603@lists.php.net to get a copy of this message | ||
Note Submitter: Fabi K
----
So here a short script that will count the letters in an utf8-string. This will work for the whole
utf-8 character set.
function strlen_utf8(&$str) {
while($str[$i]) {
$cnt = $cnt = countLeadingBits(ord($str[$i]));
$i += $cnt>0 ? $cnt : 1; // skip following bytes if the char was bigger than a Byte.
$diff += $cnt>0 ? $cnt-1 : 0; // counting every skipped Byte.
}
return ($i - $diff);
}
define(FIRST_BIT, 0x80);
/**
This function counts the leading 'on'-Bits in a Byte.
@param char The byte to analyse. Must be a number. Use ord() to analyse characters.
@return The number of leading bits that where set (1).
*/
function countLeadingBits($char) {
$char = $char & 255; // deleting 'on'-bits that where greater than 2^8 =>
every number is less or equal 0xff(255)
//echo sprintf("%08d ", decbin($char));
if( (FIRST_BIT & $char) === FIRST_BIT) { // a leading Bit is found
return countLeadingBits($char << 1) + 1;
}
return 0;
}
$testdata = "abcABC123äöüÄÖÜ";