How to Limit the Number Words to Output in PHP

Date Posted: April 27, 2014, 12:42 pm

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);

About author

Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

Hire Me