php

Select first n words of a sentence in PHP

<?php
    $n = 10; //HOW MANY WORDS YOU WANT
    $first_n_words = implode(' ', array_slice(explode(' ', $sentence), 0, $n));

    //TO ADD SUPPORT FOR WROD BREAK AND COMMAS
    function get_n_words($sentence, $count = $n) {
        preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
        return $matches[0];
    }
?>

Sometimes it is required to get first n words from a sentence to show a small description on a webpage. Using PHP you can easily do that by using above code.

Was this helpful?