Home > Mobile >  PHP Compare two strings and display the difference while preserving their original character positio
PHP Compare two strings and display the difference while preserving their original character positio

Time:10-13

For this I have been trying things myself and trying to find answers online for a while now. What I would like to achieve, is to compare two strings and display the difference in characters as an integer, whilst preserving the character positions. Basically, I have a question and answer app, and I need to compare the correct answer to the given answer. So, for example:

$correct = 'Monday';
$answer =  'Manday';

In the above example there is only one error made, so when comparing the $correct and $answer strings, I need to display "1".

I tried using strcmp, but that is not giving me the correct results. For the above example, doing strcmp($original, $answer) would give me this result: 3584.

Also when using similar_text I do not get the results I need. Example, when using similar_text($original,$answer), while using the above Monday and Manday example, it gives an expected result of 5 characters that are similar, out of 6. But when I do the following, it still gives me 1 as a result, while it should be 0 (for my case):

similar_text("Hello", "World") // The "o" is matched, but it is in the wrong position

So, in short, what I need to achieve is this. I have a correct answer, and a user input given answer. I want to compare the user given answer against the original correct answer. And how do I want to compare them? I want to compare each character position from both strings, and for all characters that are incorrect, I want to return the total wrong characters as an integer.

Some more examples:

$str1 = 'Monday';
$str2 = 'Mondayy';

The above should return '1', because the second string has an extra character. So 1 error in total.

$str1 = 'Monday';
$str2 = 'Manday';

The above should return '1', because the second string has a one wrong character. So 1 error in total.

$str1 = 'Hello';
$str2 = 'World';

The above should return '5', because the second string does not match any of the first string's characters in their position. So 5 errors in total.

CodePudding user response:

You want to use levenshtein() instead of similar_text()

similar_text() just calculates the longest matching substring. levenshtein() calculates how many characters have to be replaced to match the answer.

https://www.php.net/manual/en/function.levenshtein.php

  •  Tags:  
  • php
  • Related