0

如果你有

$str1 = "h*llo";
$str2 = "hello";

是否可以快速比较它们而无需首先从 str1 中删除 *,以及从 str2 中删除匹配的索引字符?

无论字符串中有多少 *,该解决方案都需要工作,例如:

$str1 = "h*l*o";
$str2 = "hello";

谢谢参观。

4

2 回答 2

3

是的,使用正则表达式,更具体地说是 PHP 的preg_match。您正在寻找的是“通配符”。

这是未经测试的,但应该适合你:

$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";
}
于 2013-10-15T03:17:12.397 回答
1

您可以使用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 SIMILAR TEXT

于 2013-10-15T03:25:36.660 回答