For example:

$s1 = "Test Test the rest of string"
$s2 = "Test the rest of string"

I would like to match positively $s1 but not $s2, because first word in $s1 is the same as second. Word 'Test' is example, regular expression should work on any words.

Accepted Answer

if(preg_match('/^(\w+)\s+\1\b/',$input)) {
  // $input has same first two words.
}

Explanation:

^    : Start anchor
(    : Start of capturing group
 \w+ : A word
)    : End of capturing group
\s+  : One or more whitespace
\1   : Back reference to the first word
\b   : Word boundary
Written by codaddict
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki