Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two strings in php and show character differences

Hi I am struggling to get this right:

I want to compare two strings and calculate their score in php.

What that means is I have two strings:

$string1="example1"; $string2="exumple22";

Now I want to compare the strings if they are equal - in this case they are not.

But additionally I want to see the characters that match. At least count them.

In this case that would be: 6;

I have tried this but I am stuck hers is my example:

enter code here
<?  
include("connect.php");
$query="SELECT * FROM data where ID = '1'";
$result = mysql_query($query) or die(mysql_error());


while($row = mysql_fetch_array($result))
{
    //echo "Score :{$row['scoreA']} <br>" ;
    $scoretemp=$row['scoreA'];
    $string1=$row['textA1'];
    $string2=$row['textA2'];


} 
mysql_close();

if (strcmp($string1, $string2) != 0){
    echo "not equal in a case-sensitive string comparison <br>";
$j = strlen($string1);
    for ($i = 0; $i < $j; $i++) {
    $stringtemp1++;
    echo $string1[$i].', ';
    echo $stringtemp1;
    }    

    $u = strlen($string2);
    for ($t = 0; $t < $u; $t++) {
    $stringtemp2++;
    echo $string2[$t].', ';
    echo $stringtemp2;
    }$scoreA=($stringtemp1 - $stringtemp2);    
    $stringtemp1=0;$stringtemp2=0;
}
else{
    echo "Stringmatch! <br>";
        $e = strlen($string1);
        for ($r = 0; $r < $e; $r++) {
        $stringtemp1++;
        echo $string1[$r].', ';
        echo $stringtemp1;
}$scoreA=$stringtemp1;
$stringtemp1=0;
}
 ?>
like image 819
user1091883 Avatar asked Jun 05 '12 18:06

user1091883


2 Answers

See http://www.php.net/manual/en/function.similar-text.php for how to use similar_text($str1, $str2)

This will give you the number of matching chars in both strings.

<?php
    echo similar_text("Hello World","Hello Peter");
?>

will give you 7 (the number of characters in common).

like image 62
js1568 Avatar answered Sep 24 '22 01:09

js1568


Try this

<?php

$string1 = 'example1';
$string2 = 'exumple22';

$matchingcharacters = [];
$mismatchingcharacters = [];

$len1 = strlen($string1);
$len2 = strlen($string2);

$similarity = $i = $j = $dissimilarity = 0;

while (($i < $len1) && isset($string2[$j])) {
    if ($string1[$i] == $string2[$j]) {
        $similarity++;
        $matchingcharacters[] = '['.$string1[$i].']';
    } else {
        $dissimilarity++;
        $mismatchingcharacters[] = '['.$string1[$i] . " & " . $string2[$j].']';
    }
    $i++;
    $j++;
}
echo 'First string : '.$string1.'<br>';
echo 'Second string : '.$string2.'<br>';
echo 'Similarity : ' . $similarity . '<br>';
echo 'Dissimilarity : ' . $dissimilarity . '<br>';
echo 'Matching characters : ' . implode(",", $matchingcharacters) . '<br>';
echo 'Mismatching characters : ' . implode(",", $mismatchingcharacters);
like image 23
Ajith Avatar answered Sep 24 '22 01:09

Ajith