Skip to content

Instantly share code, notes, and snippets.

@chrisveness
Created June 18, 2014 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisveness/277165d0ab6112fb1fd7 to your computer and use it in GitHub Desktop.
Save chrisveness/277165d0ab6112fb1fd7 to your computer and use it in GitHub Desktop.
Truncate text to given length with suffixed ellipsis
<?php
/**
* 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