Multibyte strings
| mb_strlen | |
| mb_substr | |
| Detect encoding | |
| mb_convert_encoding |
mb_strlen
Function strlen counts bytes while mb_strlen counts characters. For plain English both agree, but for accented letters and emoji only mb_strlen is correct.
Always pass the encoding explicitly in lessons and tools so the result does not depend on server defaults.
$text = "caf\u{E9}"; echo strlen($text); echo mb_strlen($text, "UTF-8");
mb_substr
Function substr can split a multibyte character in half and produce broken output. Function mb_substr cuts by characters and keeps the text intact.
Offsets start at zero, so position one means the second character. Length tells how many characters to keep.
$text = "h\u{E9}llo"; echo mb_substr($text, 1, 3, "UTF-8"); echo mb_substr($text, 0, 2, "UTF-8");
Detect encoding
Text from files and forms may arrive in an unknown encoding. Function mb_detect_encoding guesses the encoding from a short list that you provide.
Treat the guess as a hint and validate before storage. Strict mode returns false when the bytes do not fit any listed encoding.
$text = "hello"; echo mb_detect_encoding($text, "UTF-8, ISO-8859-1", true);
mb_convert_encoding
Normalize everything to UTF-8 right at the input boundary. Function mb_convert_encoding rewrites bytes from one encoding to another.
Convert once on the way in, then use only multibyte functions for length and slicing.
$text = "hello"; $utf8 = mb_convert_encoding($text, "UTF-8", "ISO-8859-1"); echo mb_strlen($utf8, "UTF-8");
Next: array_map, filter, reduce
Article author: Arthur Isaev