Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method for comparing strings in php

Tags:

php

I want to compare two strings and return a level of comparison.

String 1 is the input and can come in a range of formats from clients. For example:

string 1 - "GCSE English Lang Year 10" or
string 1 - "Year 10 Eng Lang GCSE" etc

String 2 is the string I want to compare it with. For example:

string 2 - "English Language"

I realise I can use preg_match to look for an exact pattern:

$subject = $inputString;
$pattern= "/Eng/";
if (preg_match($pattern, $inputString))
{
echo "match";
}

But is there a method that will return an factor of match, rather than simply yes or no? I realise there may be a more complex coding answer using the preg_match type method but I wonder if there something already around I have not found.

like image 649
RGriffiths Avatar asked Mar 10 '26 00:03

RGriffiths


1 Answers

You can use the levenshtein() function:

The Levenshtein distance is defined as the minimal number of characters you have to replace, insert or delete to transform str1 into str2. The complexity of the algorithm is O(m*n), where n and m are the length of str1 and str2 (rather good when compared to similar_text(), which is O(max(n,m)**3), but still expensive).

For example the Levenshtein distance for "English Language" and "GCSE English Lang Year 10" is 12.

$lev = levenshtein('GCSE English Lang Year 10', 'English Language');
echo $lev; // 12
like image 163
Gergo Erdosi Avatar answered Mar 11 '26 14:03

Gergo Erdosi