Dino Cagalj
Dino Cagalj

Reputation: 41

Check if there is only 1 character difference between two strings in PHP

I'm trying to figure out how to calculate whether the difference in two strings is exactly 1 character (or lack of it)

The function should cover the following cases:

STRIN1G / STRIN2G
ONE TOO THREE / ONE TWO THREE
NATALI / NATALIE
ASTRING / STRINGB

The levenshtein function (where you would check if it returns 1) would work in all cases but it wouldn't cover the last case.

Upvotes: 2

Views: 475

Answers (1)

Jeff Puckett
Jeff Puckett

Reputation: 40861

This algorithm probably won't work for all situations, but meets your given examples and should get you closer to your ultimate goal. Have a look at similar_text which is more expensive than levenshtein but more flexible. Here we'll just make an adjustment based on the varying lengths of the strings, in cases where one is a complete substring of the other.

demo: https://3v4l.org/IZ943

$strings = [
    'STRIN1G' => 'STRIN2G',
    'ONE TOO THREE' => 'ONE TWO THREE',
    'NATALI' => 'NATALIE',
    'ASTRING' => 'STRINGB',
];

foreach ($strings as $string => $variant) {
    $length = strlen($string);
    $adjustment = abs($length - strlen($variant));
    $matching = similar_text($string, $variant);
    var_dump($length - $matching + $adjustment);
}
int(1)
int(1)
int(1)
int(1)

Upvotes: 1

Related Questions