In this chapter
We'll learn why Clare's name was cut in half: what Unicode and UTF-8 are, why one character can take several bytes, how the mbstring functions — mb_strlen(), mb_substr(), mb_strtoupper() and friends — count characters instead of bytes, and how to recognise and avoid broken text like "Zoë" and "�".
The Problem in Real Life
Back to the first email of the Act. Mia runs the reminder script for Clare's booking and prints the name exactly as the SMS gets it: Clare Lef�.
The line responsible is the one from chapter 3: substr($name, 0, 10). "Count the letters," says Marcus. Mia counts on her fingers: C, l, a, r, e, a space, L, e, f, è. Ten. "So substr() should give me Clare Lefè."
"It should," says Marcus. "Now ask PHP how long her name is." strlen("Clare Lefèvre") prints 14. The name has 13 characters.
Thirteen characters, fourteen bytes. Where does the extra byte come from?
Mia
Bytes vs. Characters
Bytes, not letters
strlen() and substr() count bytes. A letter like è is two bytes, so a cut can land in the middle of it.
Every language
Names come from everywhere: Lefèvre, Zoë, Søren, 李. UTF-8 stores them all, using 1 to 4 bytes per character.
Broken text
Read the bytes with the wrong encoding and "Zoë" becomes "Zoë". Cut them in half and you get "�".
Multibyte Strings, Unicode and UTF-8
Characters are stored as numbers: a computer can only store numbers, so every character needs a number. Two standards decide how that works, and PHP has an extension for the result:
- Unicode: one big list that gives every character in every language a number, called a code point. A is U+0041, è is U+00E8, and 💈 is U+1F488.
- UTF-8: a way to store those numbers as bytes. Small numbers take one byte; bigger ones take two, three or four.
- mbstring: PHP's extension with
mb_functions that count and cut characters instead of bytes.
Unicode: before Unicode, every region had its own table of 256 characters, so the same byte meant é in one table and something else in another. Unicode fixed that with one list for the whole world: about 150,000 characters, each with its own number. The number is written as U+ followed by hexadecimal (base 16) digits, so è is U+00E8. You've already used one: \u{1F488} in chapter 1 is the code point of 💈. mb_ord() gives a character's code point, and mb_chr() turns a code point back into a character.
<?phpecho mb_ord("A"), " ", mb_ord("è"), " ", mb_ord("💈"), "\n"; // 65 232 128136printf("U+%04X\n", mb_ord("è")); // U+00E8: the same number in hexadecimalecho mb_chr(0x1F488), "\n"; // 💈
UTF-8: Unicode gives each character a number; UTF-8 decides how to store that number as bytes. It uses as few bytes as it can. The 128 basic characters — A to Z, a to z, 0 to 9 and common punctuation, the old ASCII set — take one byte each, exactly as they always did. Letters like è, ë and ø take two bytes, characters like € and most Chinese characters take three, and emoji take four. The table below shows some examples. UTF-8 is the encoding of almost the whole web, and the one to use everywhere: in your PHP files, your web pages and your database.
| Character | Code point | Bytes in UTF-8 |
|---|---|---|
| A | U+0041 | 1 |
| è | U+00E8 | 2 |
| ø | U+00F8 | 2 |
| € | U+20AC | 3 |
| 李 | U+674E | 3 |
| 💈 | U+1F488 | 4 |
<?phpforeach (["A", "è", "李", "💈"] as $char) {echo $char, ": ", strlen($char), " byte(s), ", mb_strlen($char), " character\n";}// A: 1 byte(s), 1 character// è: 2 byte(s), 1 character// 李: 3 byte(s), 1 character// 💈: 4 byte(s), 1 character$name = "Clare Lefèvre";echo strlen($name), " bytes, ", mb_strlen($name), " characters\n"; // 14 bytes, 13 charactersecho bin2hex("è"), "\n"; // c3a8: the two bytes of è, in hexadecimal
Why the name broke: strlen(), substr(), str_pad(), strtoupper() and most functions from chapters 3 and 4 work on bytes. They have no idea that two bytes belong together. substr($name, 0, 10) took nine whole characters plus the first of è's two bytes. Half a character isn't a valid character, so Clare's phone showed the replacement symbol, �. The diagram below shows the cut, byte by byte. Functions that only search for or split at plain ASCII characters, like explode(" ", ...), str_contains() and str_replace(), are safe with UTF-8. Functions that count, cut, pad or change case are not.
"Clare Lefèvre" in UTF-8: substr($name, 0, 10) cuts after byte 10, in the middle of è
C l a r e (space) L e f
9 characters, 1 byte each: bytes 1 to 9
è = two bytes: C3 A8
byte 10 is C3, byte 11 is A8
substr($name, 0, 10)
keeps C3 but drops A8: half a character, shown as �
mb_substr($name, 0, 10)
counts characters: "Clare Lefè"
<?php$name = "Clare Lefèvre";$short = substr($name, 0, 10);echo strlen($short), " bytes, ", bin2hex(substr($short, -1)), " at the end\n";// 10 bytes, c3 at the end: the first half of èvar_dump(mb_check_encoding($short, "UTF-8"));// bool(false): not valid UTF-8, so the phone shows "Clare Lef�"
mbstring: the mbstring extension (short for "multibyte string") has a character-aware version of each of those functions. mb_strlen() counts characters, mb_substr() cuts by characters, and mb_strtoupper() and mb_strtolower() change the case of every letter, not just A to Z. Newer PHP versions added more: mb_str_pad() in PHP 8.3, and mb_trim(), mb_ucfirst() and mb_lcfirst() in PHP 8.4. mb_str_split() splits a string into characters. They all use UTF-8 by default. mbstring is an extension, so check it's switched on with php -m, as in Act 01. On Ubuntu it's the package php8.5-mbstring, and on Windows the line extension=mbstring in php.ini.
<?phpecho strtoupper("zoë"), " / ", mb_strtoupper("zoë"), "\n"; // ZOë / ZOËecho ucfirst("élodie"), " / ", mb_ucfirst("élodie"), "\n"; // élodie / Élodieecho "[", str_pad("Zoë", 6, "."), "] [", mb_str_pad("Zoë", 6, "."), "]\n";// [Zoë..] [Zoë...]: str_pad() counted ë as twoecho "[", mb_trim(" Søren "), "]\n"; // [Søren]echo implode(" | ", mb_str_split("Zoë")), "\n"; // Z | o | ë
Shortening a name properly: the direct fix is mb_substr($name, 0, 10), which gives "Clare Lefè". Even better for an SMS is mb_strimwidth($name, 0, 10, "…"). It keeps the result within 10 characters including the "…", so the reader can see that the name goes on: "Clare Lef…". A name that already fits comes back unchanged. (It measures width rather than characters, so a wide character like 李 counts as two.) Characters, not bytes.
<?php$name = "Clare Lefèvre";echo mb_substr($name, 0, 10), "\n"; // Clare Lefèecho mb_strimwidth($name, 0, 10, "…"), "\n"; // Clare Lef…echo mb_strimwidth("Tom Hart", 0, 10, "…"), "\n"; // Tom Hart: short names stay as they are
Encoding problems: broken text comes in two kinds, and each one tells you what went wrong. Mojibake, like "Zoë" instead of "Zoë", means correct UTF-8 bytes were read with an old single-byte encoding: each of ë's two bytes was shown as a character of its own. � means the bytes aren't valid UTF-8 at all — half a character, or text saved in an old encoding. mb_check_encoding($s, "UTF-8") tells you whether a string is valid UTF-8, and mb_convert_encoding() converts text from another encoding. The cure is the same everywhere: save your files as UTF-8, send web pages with charset=UTF-8, and use utf8mb4 in MySQL (Act 18).
<?php// Correct UTF-8 bytes, read as an old single-byte encoding:echo mb_convert_encoding("Zoë", "UTF-8", "Windows-1252"), "\n"; // Zoëvar_dump(mb_check_encoding("Zoë", "UTF-8")); // bool(true)var_dump(mb_check_encoding("Zo\xEB", "UTF-8")); // bool(false): ë saved in an old encodingecho mb_convert_encoding("Zo\xEB", "UTF-8", "ISO-8859-1"), "\n"; // Zoë: converted to UTF-8
Characters made of several code points: one last surprise. Some things that look like a single character are really several code points. The family emoji 👨👩👧 is three people joined by two invisible "joiner" characters: five code points, so mb_strlen() says 5. Many flags work the same way. What a reader sees as one character is called a grapheme, and the intl extension's grapheme_strlen() counts those. For names and SMS text, the mb_ functions are the right tool; just know that graphemes exist. The second table below pairs each byte function with its mb_ version.
| Job | Counts bytes | Counts characters |
|---|---|---|
| Length | strlen() | mb_strlen() |
| Cut out a piece | substr() | mb_substr() |
| Find a position | strpos() | mb_strpos() |
| Upper and lower case | strtoupper(), strtolower() | mb_strtoupper(), mb_strtolower() |
| Capital first letter | ucfirst() | mb_ucfirst() (PHP 8.4) |
| Pad to a width | str_pad() | mb_str_pad() (PHP 8.3) |
| Trim both ends | trim() | mb_trim() (PHP 8.4) |
| Split into pieces | str_split() | mb_str_split() |
| Shorten with … | substr() . "…" | mb_strimwidth() |
<?php$family = "👨👩👧";echo strlen($family), " bytes\n"; // 18 bytesecho mb_strlen($family), " code points\n"; // 5 code points// grapheme_strlen($family) from the intl extension says 1
Key Takeaway
Unicode gives every character a number; UTF-8 stores it in 1 to 4 bytes. PHP's normal string functions count and cut bytes, so they can cut a character in half (�) or count è as 2. Use the mb_ functions — mb_strlen(), mb_substr(), mb_strtoupper(), mb_str_pad() — whenever you count, cut, pad or change the case of text a person typed, and keep everything in UTF-8.
Why This Matters
BookBay's customers have names like Lefèvre, Zoë, Søren and Núñez, and some will put an emoji in a note. Any code that counts, cuts or pads their text with byte functions will, sooner or later, break a name in front of the person it belongs to.
The rule is short: keep everything in UTF-8, and when you count, cut, pad or change case, use the mb_ function. The same rule comes back in Act 18, where the database must store exactly the same characters.
The reminder now uses mb_strimwidth(), and Clare's next reminder reads "Hi Clare Lef…". Olivia writes to her to apologise. That leaves the second problem from the first email: six reminders the SMS service couldn't deliver, because of phone numbers written five different ways. str_replace() can remove spaces and dashes, but it can't decide what a valid phone number is. For that, Marcus opens a new tool: regular expressions.
