UTF8 string length counter

The best way to determine the character count of a UTF8 string.

function strlen_utf8( $str )
{
   return mb_strlen( $str, 'UTF-8' );
}
 
//or...
function strlen_utf8( $str )
{
   $c = 0;
   $len = strlen( $str );
   for ( $i = 0; $i < $len; $i++ ) {
      //0x80 = 128
      $ord = ord( $str[$i] );
      if ( $ord & 0x80 ) {
         $ord <<= 1;
         while ( $ord & 0x80 ) {
            $i++;
            $ord <<= 1;
         }
 
         $c++;
      }
      else {
         $c++;
      }
   }
 
   return $c;
}

Tags

No tag here.

Recommended pages

Validate phone number...

Chek if a phone numbers is valid, according to its syntax (should be: "+390523599314"). True if it's valid, False otherwise function is_valid_phone( $phone ) { if ( $phone[0] != "+" ) { ...

Download a file from web to local...

Use this function to download a file from web to local machine. function WgetFile( $URL, $dir ) { $nomefile = $dir . "/" . basename( $URL ); if ( copy( $URL, $nomefile ) ) { retu...

Create directory function...

Create directory if not exists. function createDir( $dir ) { if ( !is_dir( $dir ) ) { mkdir( $dir, 0777 ); return true; } return false; }...

How to created mixed arguments function...

This way useful for create mixed arguments function. function foo() { $args = func_get_args(); print_r($args); }   foo(1, 1256, 6, 17); //mixed ...   -------------------Out-...