例如:
$s1 = "Test Test the rest of string"
$s2 = "Test the rest of string"
我想积极匹配$s1
而不是$s2
,因为$s1
中的第一个词与第二个词相同。单词'Test'
是示例,正则表达式应该适用于任何单词。
答案 0 :(得分:8)
if(preg_match('/^(\w+)\s+\1\b/',$input)) {
// $input has same first two words.
}
说明:
^ : 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
答案 1 :(得分:4)
~^(\w+)\s+\1(?:\W|$)~
~^(\pL+)\s+\1(?:\PL|$)~u // unicode variant
\1
是对第一个捕获组的反向引用。
答案 2 :(得分:1)
无处不在,请参阅评论......
^([^\b]+)\b\1\b
^(\B+)\b\1\b
获取第一个单词,如果在单词边界后再次重复相同的单词,则匹配。
答案 3 :(得分:1)
这不会导致Test Testx
返回true。
$string = "Test Test";
preg_match('/^(\w+)\s+\1(\b|$)/', $string);