String Preg匹配无法进行简单比较

String Preg匹配无法进行简单比较,string,preg-match,String,Preg Match,我试图使用下面的代码来比较两个字符串。preg_match doc页面显示“如果模式匹配给定主题,preg_match()将返回1”。如输出所示,即使字符串不同,结果仍然是1?请解释我的错误 $cmp_text = 'sue, smith'; $text = 'sue, smith shelly'; $pos = preg_match('/' . $cmp_text . '/', $text); if ($pos == 1) { echo 'ma

我试图使用下面的代码来比较两个字符串。preg_match doc页面显示“如果模式匹配给定主题,preg_match()将返回1”。如输出所示,即使字符串不同,结果仍然是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;
您传递给的模式是
/sue,smith/

您在
sue,smith shelly
中匹配的
sue,smith

您可以为开头的
^
和字符串结尾的
$
添加字符

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

尝试更新此行:

$pos=preg_match(“/”.$cmp_text.“/”,$text)

关于这一行:


$pos=preg_match(“/^”。$cmp_text.“$/”,$text)

谢谢。锚起作用了。但是否需要$matches?我不需要知道归还的地点和内容。我只需要知道它是否匹配,我使用$pos。这不是正确的方法吗?不,你不需要。我忘了把它取下来。是的,你可以这样做。从文档中:preg_match()如果模式与给定主题匹配,则返回1;如果不匹配,则返回0;如果发生错误,则返回FALSE。
    matched: sue, smith is the same as sue, smith shelly
    pos 1