PHP FIX IssuesCategory: PHPHow can I get the string of the first 20 words in PHP?
koentsm asked 48 years ago

How can I get the string of the first 20 words in PHP?
You might find s($str)->words(20) helpful, as found in this standalone library.

1 Answers
Laxmi Kant answered 6 years ago

change the number 2 to the number 19 below to get the first 20 words.

function first3words($s) {
return preg_replace(‘/((\w+\W*){2}(\w+))(.*)/’, ‘${1}’, $s);
}

var_dump(first3words(“hello yes, world wah ha ha”)); # => “hello yes, world”
var_dump(first3words(“hello yes,world wah ha ha”)); # => “hello yes,world”
var_dump(first3words(“hello yes world wah ha ha”)); # => “hello yes world”
var_dump(first3words(“hello yes world”)); # => “hello yes world”
var_dump(first3words(“hello yes world.”)); # => “hello yes world”
var_dump(first3words(“hello yes”)); # => “hello yes”
var_dump(first3words(“hello”)); # => “hello”
var_dump(first3words(“a”)); # => “a”
var_dump(first3words(“”)); # => “”

Author - comments - 0

Copyright © 2014 - Designed by Jolly Themes