Multibyte Strings, Unicode and UTF-8

6.Multibyte Strings, Unicode and UTF-8

M

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 "�".

15–17 min

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.

M

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.

Every character has a number
<?php
echo mb_ord("A"), " ", mb_ord("è"), " ", mb_ord("💈"), "\n"; // 65 232 128136
printf("U+%04X\n", mb_ord("è")); // U+00E8: the same number in hexadecimal
echo 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.

Table — How many bytes UTF-8 uses
CharacterCode pointBytes in UTF-8
AU+00411
èU+00E82
øU+00F82
€U+20AC3
李U+674E3
💈U+1F4884
Bytes and characters
<?php
foreach (["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 characters
echo 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

next

è = two bytes: C3 A8

byte 10 is C3, byte 11 is A8

the cut

substr($name, 0, 10)

keeps C3 but drops A8: half a character, shown as �

the fix

mb_substr($name, 0, 10)

counts characters: "Clare Lefè"

Clare's name, cut by bytes
<?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.

Byte functions and mb_ functions side by side
<?php
echo strtoupper("zoë"), " / ", mb_strtoupper("zoë"), "\n"; // ZOë / ZOË
echo ucfirst("élodie"), " / ", mb_ucfirst("élodie"), "\n"; // élodie / Élodie
echo "[", str_pad("Zoë", 6, "."), "] [", mb_str_pad("Zoë", 6, "."), "]\n";
// [Zoë..] [Zoë...]: str_pad() counted ë as two
echo "[", 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.

The fix: count characters
<?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).

Mojibake and invalid bytes
<?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 encoding
echo 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.

Table — Byte functions and their mb_ versions
JobCounts bytesCounts characters
Lengthstrlen()mb_strlen()
Cut out a piecesubstr()mb_substr()
Find a positionstrpos()mb_strpos()
Upper and lower casestrtoupper(), strtolower()mb_strtoupper(), mb_strtolower()
Capital first letterucfirst()mb_ucfirst() (PHP 8.4)
Pad to a widthstr_pad()mb_str_pad() (PHP 8.3)
Trim both endstrim()mb_trim() (PHP 8.4)
Split into piecesstr_split()mb_str_split()
Shorten with …substr() . "…"mb_strimwidth()
One emoji, five code points
<?php
$family = "👨‍👩‍👧";
echo strlen($family), " bytes\n"; // 18 bytes
echo 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.