Truncate multibyte strings safely in PHP
Shorten UTF-8 text with mb_ functions so accents and emoji are never cut in half.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?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
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.
Related snippets
- JavaScript Tested
Truncate a string with an ellipsis
Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.
- Python Tested
Slugify a string
Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.
- PHP Tested
Slugify a string in PHP
Create URL-safe lowercase slugs from titles, removing accents and punctuation.
- 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.

