首页 > 解决方案 > 比较两个字符串是否具有相似性

问题描述

我正在寻找 PHP 中的一个函数,它可以将两个字符串与数字进行比较。他们应该至少有 5 个相同的字母/数字以连续的顺序排列

示例: AD-2018-34567-234并且cd 34567 两者都包含相同的字母/数字=34567

或者

10256两者cd 10256都包含10256

或者

1234567890- rfwet043-123455-cd1234-sdf两者4edgs-cd12340e-3ed 都包含cd1234

在这里尝试使用此功能,但不符合我的需求。

$str1 = "AD-2018-34567-234";
$str2 = "cd 34567";

$str3 = "10256";
$str4 = "cd 10256";

$str5= "1234567890-rfwet043-123455-cd1234-sdf";
$str6= "4edgs-cd12340e-3ed";

if(strpos($str1, $str2) !== false) {
    echo "matched";
}else{
    echo "not matched";
}

if(strpos($str3, $str4) !== false) {
    echo "matched";
}else{
    echo "not matched";
}

if(strpos($str5, $str6) !== false) {
    echo "matched";
}else{
    echo "not matched";
}

也试过strpos了,都不配。

标签: phpfunction

解决方案


这通过循环查找字符串并且一次只使用五个字符来匹配你想要的。

$str1 = ["AD-2018-34567-234","10256","1234567890-rfwet043-123455-cd1234-sdf"];
$str2 = ["cd 34567","cd 10256","4edgs-cd12340e-3ed"];

foreach($str1 as $key => $str){
    $find = $str2[$key];
    $l = strlen($find);
    $match = false;
    for($i=0; $i<=($l-5);$i++){ // loop the find string 
        //echo $str . " " . substr($find,$i, 5) . "\n"; // debug
        if(strpos($str, substr($find,$i, 5)) !== false) { // take five characters at the time and stros them
            $match = true;
            break;
        }
    }
    if($match){
        echo "match\n";
    }else{
        echo "no match\n";
    }
}

如果您取消注释被注释的行,您将看到它是如何工作的

https://3v4l.org/unp0D


$str1 = "AD-2018-34567-234";
$find = "cd 34567";
$l = strlen($find);

$match = false;
for($i=0; $i<=($l-5);$i++){ // loop the find string 
    //echo $str1 . " " . substr($find,$i, 5) . "\n"; // debug
    if(strpos($str1, substr($find,$i, 5)) !== false) { // take five characters at the time and stros them
        $match = true;
        break;
    }
}
if($match){
    echo "match\n";
}else{
    echo "no match\n";
}

推荐阅读