How to Limit the Number Words to Output in PHP


I recently created a page that contains a list of articles. I wanted to show the title and the excerpt, but the output of the excerpt is too long and breaking my list. So here is what I did to limit the number of words:

Create a function that will accept two parameters (the text to be limited and the desired number of words)

function limit_words($text, $limit) {
    $words = explode(" ",$text);
    return implode(" ",array_splice($words,0,$limit));
}

Then we call the function to our page:

$text = "The quick brown fox jumps over the lazy dog";
 
echo limit_words($text,5);






Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.