php

Get first n words from a paragraph in PHP

You can use this code to get first n words from a paragraph or sentence

<?php
    function get_n_words($paragraph, $word_counts) {
        preg_match("/(?:w+(?:W+|$)){0,$word_counts}/", $paragraph, $matches);
        return $matches[0];
    }

    get_n_words("This is a long paragraph", 2); //TO SELECT FIRST 2 WORDS
    get_n_words("This is a long paragraph", 10); //TO SELECT FIRST 10 WORDS
?>

PHP inbuilt function preg_match() is the best way to get the first n words from a paragraph or big sentence. You just need to pass $word_counts in the above function and it will return you the sentence made with the first n words.

Was this helpful?