note 58282 added to function.strlen

From: Date: Sat, 29 Oct 2005 22:08:53 +0000
Subject: note 58282 added to function.strlen
Groups: php.notes 
Request: Send a blank email to php-notes+get-97808@lists.php.net to get a copy of this message
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äöüÄÖ܀"; ---- Manual Page -- http://www.php.net/manual/en/function.strlen.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+58282 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+58282&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+58282&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#97808) next »