Back to results for “Validation”
PHP › Strings & String Functions

Why are the multibyte string functions, such as mb_strlen and mb_substr, important when working with text that contains non ASCII characters like accented letters or emoji?

Intermediate

Answer

PHP's original string functions were designed around the assumption that every character occupies exactly one byte, which works fine for plain English text using the ASCII character set, but breaks down when working with UTF-8 encoded text containing accented letters, characters from non Latin alphabets, or emoji, since these characters can occupy multiple bytes each, and using a regular function like strlen on such text would return an inaccurate character count, whereas the multibyte equivalent, mb_strlen, correctly counts actual characters rather than raw bytes.
$text = 'Café';
echo strlen($text);     // Outputs 5 (byte count)
echo mb_strlen($text);  // Outputs 4 (character count)
Real-world example An international user registration form uses mb_strlen instead of strlen to validate a maximum name length, correctly counting the actual number of characters even for names containing accented letters common in many European languages.

Common follow-ups: How do you configure the default internal encoding used by the multibyte string functions?;What other common string functions have multibyte equivalents besides strlen and substr?