如果你有
$str1 = "h*llo";
$str2 = "hello";
是否可以快速比较它们,而无需首先从 str1 中删除 *,从 str2 中删除匹配的索引字符?
无论字符串中有多少 *,解决方案都需要工作,例如:
$str1 = "h*l*o";
$str2 = "hello";
感谢您的观看。
是的,使用正则表达式,更具体地说,preg_match PHP 的。您正在寻找的是"通配符"。
这是未经测试的,但应该适合您:
$str1 = "h*llo";
$str2 = "hello";
//periods are a wildcards in regex
if(preg_match("/" . preg_quote(str_replace("*", ".*", $str1), "/") . "/", $str2)){
echo "Match!";
} else {
echo "No match";
}
编辑:这应该适用于您的情况:
$str1 = "M<ter";
$str2 = "Moter";
//periods are a wildcards in regex
if(preg_match("/" . str_replace("'<", ".*", preg_quote($str1, "/")) . "/", $str2)){
echo "Match!";
} else {
echo "No match";
}
您可以使用
similar_text()
来比较两个字符串,如果结果高于例如 80%,则接受。
similar_text($str1, $str2, $percent);
例:
$str1 = 'AAA';
$str1 = '99999';
similar_text($str1, $str2, $percent);
echo $percent; // e.g. 0.000
$str1 = "h*llo";
$str2 = "hello";
similar_text($str1, $str2, $percent);
echo $percent; // e.g. 95.000
在此处查看更多 PHP 类似文本