0

I have two strings I need to compare. Let's say for example that the strings are as follows:

$A = "A fox jumped over the log";
$B = "A fox jumped";

Now how would I compare these two strings in PHP in order to return a percentage of character matching.

So I would like my algorithm to return (for the example above):

10/20 or .5 since $B has exactly half of the matches of the length of $A.

I figured I could iterate through each character, but this seemed a bit tedious and my research indicated that preg_match wouldn't help me much here.

3
  • if a character appears twice in the first string but only once in the second string is that 1/2 or 2/2? Commented Sep 27, 2011 at 23:46
  • also, does position matter? if you have a fox jumped and _a fox jumped is that a 0% match because the second string is offset by 1? Commented Sep 27, 2011 at 23:52
  • I updated my question to be more clear. In my case, string B will always be the first part of string A. So I need to detect if a string (lets say string X) is contained within string A. If so, it will look like string B Commented Sep 27, 2011 at 23:52

1 Answer 1

4

Try the levenshtein or similar_text functions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.