为什么我的preg_match不起作用?

时间:2015-12-02 10:24:47

标签: php preg-match

这是我的代码:

if(preg_match("/(sleep|drink|beep|@|.com)/i", $content)){
     // get candy
}

如果$content字符串包含单词sleepdrinkbeep或字符@或{{}},我会尝试获取一些糖果{1}}。

适用于前3个字,但不适用于.com@。我在这里做错了什么?

1 个答案:

答案 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