Home > Back-end >  How to get the part of a string that doesn't match another in PHP?
How to get the part of a string that doesn't match another in PHP?

Time:10-03

I've been using similar_text to compare two different strings, however instead of knowing how similar they are, I'd rather figure out exactly which part of the string doesn't match the other.

For example:

$str1 = "The cat was happy";
$str2 = "The cat is happy";

custom_function($str1, $str2);

The function should return "is", since that is the only part of $str2 that doesn't match $str1.

Does anyone know of a way in PHP to do this?

Thanks.

CodePudding user response:

You can split the strings into words and compare resulting arrays in next way:

function custom_function(string $str1, string $str2) : array {

    $arr1 = explode(' ', $str1);
    $arr2 = explode(' ', $str2);
    
    return array_combine(array_diff($arr1, $arr2), array_diff($arr2, $arr1));
}

php code online

CodePudding user response:

I am not sure what exactly did you mean, so this is another potential solution:

function custom_function(string $str1,string $str2):string{
    $o="";
    $i=0;
    $j=0;
    $l1=strlen($str1);
    $l2=strlen($str2);
    while($i<$l1&&$j<$l2){
        if($str1[$i]===$str2[$j]){
            $i  ;
            $j  ;
        }else{
            $o.=$str2[$j];
            while($str1[$i]!==$str2[$j]&&$i<$l1) $i  ;
        }
    }
    return $o;
}

CodePudding user response:

Maybe this:

function custom_function(string $str1, string $str2):string{
    $o="";
    $i=0;
    while($str1[$i]===$str2[$i]) $i  ;
    $j=strlen($str1)-1;
    $k=strlen($str2)-1;
    while($str1[$j]===$str2[$k]&&$j-->=0&&$k-->=0);
    unset($j);
    while($i<=$k) $o.=$str2[$i  ];
    return $o;
}
  • Related