PHP - 如何比较相似数据


PHP - How To Compare Alike Data?

在PHP中,如何比较两个"相似"的数据?例如,在此代码中:

$a = "cats are cool";
$b = "1. catS are cool!!!"
if($a == $b) {
    echo "TRUE";
}
else {
    echo "FALSE";
}

现在明显的输出将是"FALSE"。但就我想要实现的目标而言,只要关键字"猫很酷"$b,结果应该是"TRUE"。我该怎么做?

如果要查找完全匹配项,请使用 stripos()

//Note the use of !== here, it's because stripos may return 0,
//Which would be interpreted as false without strict comparison.
if (stripos($string, "cats are cool") !== false) {
    //Cats are cool indeed.
}

你必须定义你自己的逻辑,句号。要么查找关键字[例如,搜索字符串中弹出的白名单出现次数],要么计算一些字符串距离指标,例如Levenshtein距离。

如果你应该在第二个字符串中找到第一个字符串,你可以使用strpos

使用stripos()

if(stripos($b,$a) !== FALSE)
echo "found";
else
echo "not found";