2015-12-02 47 views
-2

这里是我的代码:为什么不工作我的preg_match?

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

我试图做得到一些糖果,如果$content字符串包含单词sleepdrinkbeep或字符@.com

它适用于第3个字,而不是为@.com。我在这里做错了什么?

+1

'/'='|!'这是不一样的性格 – Rizier123

+0

逃亡'.'它是一个特殊字符。 – Rizier123

回答

0

你的代码是正确的,做工精细,像这样的例子脚本和输出:

<?php 

$contents = [ 
    'go to sleep', 
    'I will drink water', 
    'this is a beep', 
    '[email protected]', 
    '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 "[email protected]" 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