Created
March 12, 2024 18:46
-
-
Save artlung/7ec7e93cb4b8849f271c941e8b366860 to your computer and use it in GitHub Desktop.
Yet another PHP excerpt function
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
/** | |
* @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