为什么不工作我的preg_match?
问题描述:
这里是我的代码:为什么不工作我的preg_match?
if(preg_match("/(sleep|drink|beep|@|.com)/i", $content)){
// get candy
}
我试图做得到一些糖果,如果$content
字符串包含单词sleep
,drink
,beep
或字符@
或.com
。
它适用于第3个字,而不是为@
或.com
。我在这里做错了什么?
答
你的代码是正确的,做工精细,像这样的例子脚本和输出:
<?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)
'/'='|!'这是不一样的性格 – Rizier123
逃亡'.'它是一个特殊字符。 – Rizier123