How to print first two words of a sentence in php

39 views Asked by At

I wanna print the first two words of a sentence,

$txt = "Laravel PHP Node JS";

and expecting the output Laravel PHP

used below snippet is there any other way to simplify it?

echo (implode(array_slice(preg_split("/\s+/", $txt), 0, 2),' '));
1

There are 1 answers

0
The fourth bird On

If with simpler you mean a single function call, you might for example match the first 2 "words" by matching 2 times one or more non whitespace characters with \S+ with preg_match and check if there is a match.

$txt = "Laravel PHP Node JS";
if (preg_match("/\S+\h+\S+/", $txt, $match)) {
    echo $match[0];
}

Output

Laravel PHP