[英]Regular expression to check if two first words are same
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. 我想积极匹配
$s1
而不是$s2
,因为$s1
中的第一个字与第二个相同。 Word 'Test'
is example, regular expression should work on any words. 单词
'Test'
是示例,正则表达式应该适用于任何单词。
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
~^(\w+)\s+\1(?:\W|$)~
~^(\pL+)\s+\1(?:\PL|$)~u // unicode variant
\\1
is a back reference to the first capturing group. \\1
是第一个捕获组的后向引用。
Not working everywhere, see the comments... 不在任何地方工作,请参阅评论......
^([^\b]+)\b\1\b
^(\B+)\b\1\b
Gets the first word, and matches if the same word is repeated again after a word boundary. 获取第一个单词,如果在单词边界后再次重复相同的单词,则匹配。
This does not cause Test Testx
to return true. 这不会导致
Test Testx
返回true。
$string = "Test Test";
preg_match('/^(\w+)\s+\1(\b|$)/', $string);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.