compare two strings in php and show character differences

character, compare, match, php, string

Solution

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).

Problem

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; } ?> ```

Original source