Created
June 18, 2014 08:28
-
-
Save chrisveness/277165d0ab6112fb1fd7 to your computer and use it in GitHub Desktop.
Truncate text to given length with suffixed ellipsis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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