52 of 410 menu

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 accepts the string as the first parameter and the encoding as the second (optional) parameter.

Syntax

mb_strlen(string, [encoding]);

Example

Counting string length in UTF-8:

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

Code execution result:

6

Example

Comparison with strlen for Cyrillic:

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

Code execution result:

strlen: 8 mb_strlen: 4

Example

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

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

Code execution result:

5

See Also

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