预匹配失败简单比较

Preg match fails simple compare

我正在尝试使用下面的代码来比较两个字符串。 preg_match 文档页面显示 "preg_match() returns 1 if the pattern matches given subject"。如输出所示,即使字符串不同,结果也是 1?请解释我的错误。

    $cmp_text = 'sue, smith';
    $text = 'sue, smith shelly';

    $pos = preg_match('/' . $cmp_text . '/', $text); 
    if ($pos == 1) { 
      echo 'matched: ' . $cmp_text . ' is the same as ' . $text . '<br>';
    } else echo 'no match';

    echo 'pos '.$pos;

上面的输出是

    matched: sue, smith is the same as sue, smith shelly
    pos 1

您要传递给 preg_match 的内容,因为模式是 /sue, smith/

您正在 sue, smith shelly 中匹配 sue, smith,这将 find a match

您可以 add anchors 作为开头 ^ 和字符串结尾 $

然后你传递给 preg_match 的模式将是 /^sue, smith$/

尝试更新这一行:

$pos = preg_match('/' . $cmp_text . '/', $text);

到这一行:

$pos = preg_match('/^' . $cmp_text . '$/', $text);