PHP 8 Intermediate Language Basics · 6 min read

mb_substr for Multibyte Titles

Lesson 42 of 43 in the PHP 8 learning path.

How do I shorten a title without splitting a character?

mb_substr counts characters, not bytes. substr counts bytes and can split UTF-8.

A title that ends with an accented character or an emoji becomes invalid UTF-8 if you cut it with substr.

Syntax & Parameters

Syntax
mb_substr($title, 0, 40)

Example

src/Blurb.php
<?php
declare(strict_types=1);
function preview(string $title, int $limit = 12): string
{
    if (mb_strlen($title) <= $limit) {
        return $title;
    }
    return rtrim(mb_substr($title, 0, $limit - 1)) . "…";
}
echo preview("Café routes"), PHP_EOL;
echo preview("Short"), PHP_EOL;
echo strlen(substr("Café", 0, 3)), PHP_EOL;
echo mb_strlen(mb_substr("Café", 0, 3)), PHP_EOL;

Expected Output

Café route…
Short
3
3

Line-by-Line Walkthrough

  1. The limit is a character count.
  2. Short titles are returned whole.
  3. mb_substr takes the first characters.
  4. A single ellipsis character is added after a trim.
  5. Café routes is shortened by characters.
  6. Short stays Short.
  7. substr on Café can cut a byte sequence.
  8. mb_strlen of the multibyte slice counts characters.

Common Pitfalls & Security

Check this before you copy it.

  • substr will split a multibyte character and store invalid UTF-8.
  • The ellipsis counts as a character if you forget to reserve room for it.
  • mb_substr needs the mbstring extension, which is normal on current PHP.
  • A character limit is not a pixel width. A wide letter still takes more space.

Best Practices & Modern Standards

Use mb_strlen and mb_substr for titles and names.

Reserve one character for the ellipsis when you truncate.

Real-World Use

A catalog card shortens a long lesson title to 40 characters without corrupting the last letter.

Frequently Asked Questions

Why not substr?

substr counts bytes. A UTF-8 character can be more than one byte.

Does the ellipsis have to be three dots?

Use one ellipsis character so the count stays honest.

What if mbstring is missing?

Install it. Do not fall back to substr for names.

Is this a layout width?

No. It is a character cap. CSS handles the visual width.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…