The mb_strlen Function

The mb_strlen function returns the number of characters in a string, working correctly with multibyte encodings (for example, UTF-8). Unlike strlen, it correctly counts characters that occupy multiple bytes. It takes the string as the first parameter and the encoding as the second (optional) one.

Syntax

phpmb_strlen(string, [encoding]);

Example

Counting string length in UTF-8:

php<?php
  $res = mb_strlen('Привет', 'UTF-8');
  echo $res;
?>

Code execution result:

php6

Example

Comparison with strlen for Cyrillic:

php<?php
  $str = 'тест';
  echo 'strlen: ' . strlen($str) . '<br>';
  echo 'mb_strlen: ' . mb_strlen($str, 'UTF-8');
?>

Code execution result:

phpstrlen: 8
mb_strlen: 4

Example

Usage without specifying encoding (encoding is taken from mb_internal_encoding):

php<?php
  echo mb_strlen('abcde');
?>

Code execution result:

php5

See Also

  • the strlen function,
    which returns the string length in bytes
  • the mb_substr function,
    which extracts a substring taking encoding into account