Search code snippets, questions, articles...

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
?>
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

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.

Search Index Data (The code snippet can also be found with below search text)

Select first 10 words from string in PHP
Was this helpful?
0 Comments