This is a little helpful function I wrote in PHP to make a
content snippet that tries to prevent cutting off halfway through a
word. It keeps the number of words to a given amount and also restricts
the text to a specfic length if the words go over the character limit.
It is pretty simple but works great!
There you go, happy coding!
function excerpt($text, $words=12, $end='...',$limit=120) {
// split the string by spaces into an array
$split = explode(' ',$text);
if (count($split)>$words) {
// rebuild the excerpt back into a string
$text = join(' ',array_slice($split,0,$words));
}
// append the ending, limit it, and return
return substr($text,0,$limit-length($end)).$end;
}
Where does the length() function come from? I put 3 instead of it. By the way, this still cuts off words.
ReplyDeleteI'm not sure... the strlen() should work as a replacement.
Delete