这是我的代码:
if(preg_match("/(sleep|drink|beep|@|.com)/i", $content)){
// get candy
}
如果$content
字符串包含单词sleep
,drink
,beep
或字符@
或{{}},我会尝试获取一些糖果{1}}。
适用于前3个字,但不适用于.com
或@
。我在这里做错了什么?
答案 0 :(得分:0)
您的代码是正确的,并且可以正常工作,例如此示例脚本和输出:
<?php
$contents = [
'go to sleep',
'I will drink water',
'this is a beep',
'test@test.uk',
'google.com',
'endswithcom',
'this doesn\'t match'
];
foreach ($contents as $content) {
print "content \"$content\" ";
if (preg_match("/(sleep|drink|beep|@|\\.com)/i", $content)) {
print " match\n";
} else {
print " doesn't match\n";
}
}
输出:
content "go to sleep" match
content "I will drink water" match
content "this is a beep" match
content "test@test.uk" match
content "google.com" match
content "endswithcom" doesn't match
content "this doesn't match" doesn't match
就像@ Rizier123解释的那样,我使用的是\\.com
而不是.com
因为。{ (点)是一个特殊字符,表示任何字符,在我们的示例中,如果我们不转义点字符,内容endswithcom
将匹配。 (见PCRE regex dot syntax)