Skip to content
GreenSnippets

Truncate multibyte strings safely in PHP

Shorten UTF-8 text with mb_ functions so accents and emoji are never cut in half.

PHP
<?php
function truncate(string $text, int $max, string $ellipsis = '…'): string
{
    if (mb_strlen($text) <= $max) {
        return $text;
    }
    $room = max(0, $max - mb_strlen($ellipsis));
    return rtrim(mb_substr($text, 0, $room)) . $ellipsis;
}

Example / expected output

Output
truncate('Crème brûlée recipe', 10); // "Crème brû…"

How it works

substr and strlen count bytes and can leave an invalid UTF-8 sequence at the cut. The mb_ functions count characters. The helper keeps the total length including the ellipsis within $max.

  • Python Tested

    Slugify a string

    Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.

  • JavaScript Tested

    Slugify a string for URLs

    Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.