PHP

Truncate Text with Ellipsis (word-safe)

admin by @admin ADMIN
4m ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Cleanly truncate a string to a max length without breaking words mid-character. Adds a trailing ellipsis when truncated and never exceeds the requested length including the ellipsis.
PHP
Raw
<?php
function truncateWords(string $text, int $maxLen, string $ellipsis = '…'): string {
    $text = trim($text);
    if (mb_strlen($text) <= $maxLen) return $text;

    $budget = $maxLen - mb_strlen($ellipsis);
    if ($budget <= 0) return mb_substr($ellipsis, 0, $maxLen);

    $cut = mb_substr($text, 0, $budget);
    // back off to the last word boundary so we don't cut mid-word
    $lastSpace = mb_strrpos($cut, ' ');
    if ($lastSpace !== false && $lastSpace > $budget * 0.5) {
        $cut = mb_substr($cut, 0, $lastSpace);
    }
    return rtrim($cut, " ,.;:") . $ellipsis;
}

echo truncateWords("The quick brown fox jumps over the lazy dog", 20);
// The quick brown fox…
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.