A lot of code uses strlen to get the size of a string. The problem: strlen returns the number of bytes, not the number of characters. As soon as a string contains accented letters or emojis, the result is wrong.
The problem with strlen
In UTF-8, a character such as “é” takes two bytes, so strlen counts it as two:
echo strlen('café'); // 5 (not 4)
echo mb_strlen('café'); // 4The solution: mb_strlen
The mb_strlen function, provided by the mbstring extension, takes the encoding into account and returns the real number of characters:
mb_strlen($string, 'UTF-8');
Always pass the encoding as the second argument. Without it, mb_strlen uses PHP’s internal encoding, which is not necessarily the one of your string.
What to avoid
You sometimes see this trick used as a workaround:
strlen(utf8_encode($string));
Do not use it anymore: utf8_encode() has been deprecated since PHP 8.2 and is on its way out. mb_strlen does the job cleanly, in a single call.
Going further
The mbstring extension offers a whole set of encoding-aware equivalents: mb_substr, mb_strtoupper, mb_strpos, and so on. Whenever you handle text that may contain UTF-8, prefer them over their str* counterparts.
