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?
Similar Posts
- Get first n words from a paragraph in PHP
- PHP OOP insert, select from DB
- Lowercase first character of a String in PHP
- Uppercase first character of a String in PHP
- Uppercase first character of each word of a String in PHP
- Convert characters to lowercase using strtolower() function in PHP
- Check empty string in PHP