Skip to content
Tutorials Center
My learning

Topics

PHP Reference · String Functions

PHP mb_strlen() function

Reference for PHP mb_strlen(): count the characters of a multibyte string, how it differs from strlen(), the encoding argument and invalid input.

mb_strlen() returns the number of characters in a string, interpreted in a given character encoding. Where strlen() counts bytes, mb_strlen() counts code points, so "日本語" is 3 rather than 9.

It belongs to the mbstring extension. The encoding defaults to the value of mb_internal_encoding(), which is UTF-8 in modern PHP.

PHP
<?php
echo strlen("naïve");      // 6
echo mb_strlen("naïve");   // 5

Try it

PHP Counting characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Limits and combining characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
mb_strlen(string $string, ?string $encoding = null): int
Name Description
$string The string to measure.
$encoding The character encoding, such as "UTF-8". If null, the internal encoding is used.

Return value: the number of characters as an integer.

Errors: a ValueError is thrown if $encoding is not a valid encoding name.

Usage notes

  • Code points, not visible glyphs. A letter plus a combining accent counts as 2, and many emoji sequences (flags, skin tones, families) count as several. For user-perceived characters use grapheme_strlen() from the intl extension, when installed.
  • Invalid bytes. Bytes that are not valid in the encoding are counted in an implementation-defined way (each is usually counted as one character), so validate input first with mb_check_encoding().
  • Slower than strlen(). It has to walk the string; use strlen() for byte limits, binary data and ASCII-only values.
  • Always agree on the encoding. Save files, database connections and HTTP responses as UTF-8, and pass the encoding explicitly when working with other encodings.
  • Pair with other mb_ functions. mb_substr(), mb_strpos() and mb_str_split() use the same character positions.
  • Requires mbstring. Almost every PHP build ships it, but it is a separate extension that can be disabled.