Skip to content

Instantly share code, notes, and snippets.

@artlung
Created March 12, 2024 18:46
Show Gist options
  • Save artlung/7ec7e93cb4b8849f271c941e8b366860 to your computer and use it in GitHub Desktop.
Save artlung/7ec7e93cb4b8849f271c941e8b366860 to your computer and use it in GitHub Desktop.
Yet another PHP excerpt function
/**
* @param $text
* @param int $maxLength (default 200 characters)
* @param string $ending (characters to append to the end of the excerpt)
* @return string
*/
function excerpt($text, int $maxLength = 200, string $ending = '...'): string
{
// collapse whitespace
$text = preg_replace('/\s+/', ' ', $text);
// strip tags
$text = strip_tags(trim($text));
// split on spaces...
$words = explode(' ', $text);
$outputString = '';
$spacer = ' ';
$characterCount = 0;
// account for the suffix
$maxLength = $maxLength - strlen($ending);
// add words only if we are under the length
for ($i = 0; $i < count($words); $i++) {
$word = $words[$i];
$characterCount += strlen($word) + strlen($spacer);
if ($characterCount > $maxLength) {
break;
}
$outputString .= $word . $spacer;
}
if ($characterCount > $maxLength) {
$outputString = rtrim($outputString) . $ending;
}
return $outputString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment