Regular expression to check if two first words are same

前端 未结 4 848
别跟我提以往
别跟我提以往 2021-01-13 04:15

For example:

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

I would like to match positively $s1 but

4条回答
  •  别那么骄傲
    2021-01-13 05:14

    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
    

提交回复
热议问题