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

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...

Extract numbers from a unicode string...

Quick extract numbers from a unicode string......

Detect leap year...

Detect leap year for gregorian and shamsi date. function gLeapYear($year) { if (($year % 4 == 0) and (($year % 100 != 0) or ($year % 400 == 0))) return true; else return ...

URL Checker...

This function check if an url is valid or not. function is_valid_url($url) { return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url); }...