我正在尝试使用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。
答案 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';
}