<?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…
Create a free account and build your private vault. Share publicly whenever you want.