如果相似,则将两个字符串与数字进行比较

时间:2018-07-25 08:44:07

标签: php function

我正在寻找PHP中的一个函数,该函数可以比较两个带数字的字符串。它们应按连续的顺序至少5个相同的字母/数字。

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

OR

10256cd 10256都包含10256

OR

1234567890- rfwet043-123455-cd1234-sdf4edgs-cd12340e-3ed 两者都包含cd1234

尝试使用此function here,但不符合我的需求。

$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尝试了所有不匹配的内容。

2 个答案:

答案 0 :(得分:1)

这可以通过循环查找字符串并同时仅使用五个字符来完成您想要的操作。

$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";
}

答案 1 :(得分:0)

尝试此解决方案

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

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

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

$val=similar_text($str1, $str2,$per);
if($val>=5){
    echo "Matched";
}else{
    echo "Not matched";
}

$val=similar_text($str3, $str4,$per);
if($val>=5){
    echo "Matched";
}else{
    echo "Not matched";
}

$val=similar_text($str5, $str6,$per);
if($val>=5){
    echo "Matched";
}else{
    echo "Not matched";
}