PHP正则表达式匹配句子

时间:2017-08-15 12:29:08

标签: php regex

我正在尝试使用PHP和正则表达式来比较两个句子:

$data = "I am a happy man with 2 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';}

这似乎工作正常,但如果我将句子更改为:

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*2)(?=.*kids)/i', $data)) {echo 'match';} else {echo 'not match';}

它还在说匹配。问题是,不匹配确切的数字,只检查另一个句子上是否有数字2。

1 个答案:

答案 0 :(得分:4)

添加字边界:

Call to a member function isEmpty() on a non-object

您可能还希望在每个前瞻中添加,但正则表达式将变得不可用

$data = "I am a happy man with 20 kids";
if (preg_match('/^(?=.*I)(?=.*am)(?=.*happy)(?=.*with)(?=.*\b2\b)(?=.*kids)/i', $data)) {
//                                                 here ___^^ ^^
    echo 'match';
} else {
    echo 'not match';
}