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.
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(“”)); # => “”
Please login or Register to submit your answer
Author - comments - 0