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

Gregorian to Persian Date Convertor...

Gregorian to Persian Date Convertor....

Random string generator...

Random string generator. Optionally, you can give it a desired string length. function rnd_string($len = 24) { $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $str...

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