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)

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

Then we call the function to our page:

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


Do you need help with a project? or have a new project in mind that you need help with?

Contact Me