Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Truncate text to given length with suffixed ellipsis
* Truncates text to given length with suffixed ellipsis.
* @param string $text Original text string.
* @param int $length Length to truncate to.
* @param bool [$wholeWords=true] Whether to truncate back to whole words.
* @return string Truncated string.
function truncate($text, $length, $wholeWords=true)
if (strlen($text) <= $length) return $text; // no-op
// if not whole words, simply truncate to length
if (!$wholeWords) return substr($text, 0, $length).'';
// truncate to length+1 (to check if last word is whole)
$text = substr($text, 0, $length+1);
// remove trailing truncated word to leave whole words only
$m = preg_match('/(.+)\b\w+$/', $text, $match);
$text = $m ? $match[1] : $text;
// remove any trailing whitespace/punctuation
// (or trailing extra character if there was only one word)
$m = preg_match('/(.+)\b\W+$/', $text, $match);
$text = $m ? $match[1] : substr($text, 0, $length);
return $text.'';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.