Calcula la similitud entre los dos strings string1
y string2, según el método descrito en
Programming Classics: Implementing the World's Best Algorithms by Oliver (ISBN 0-131-00413-1). Se debe tener en cuenta
que esta implementación no utiliza el método de pila como en el
pseudocódigo de Oliver, sino llamadas recursivas, lo que puede acelerar o no
el proceso. Se debe tener en cuenta que la complejidad del algoritmo es de O(N**3) donde
N es el tamaño del string más grande.
Invertir string1 y
string2 puede producir resultados diferentes;
ver el ejemplo a continuación.
percent
Al pasar una referencia como tercer argumento,
similar_text() calculará la similitud en
porcentaje, dividiendo el resultado de similar_text()
por la media de la longitud de los strings proporcionados multiplicado
por 100.
Devuelve el número de caracteres coincidentes en los dos strings.
El número de caracteres coincidentes se calcula encontrando la primera subcadena común más larga, y luego haciendo esto para los prefijos y sufijos,
de forma recursiva. Las longitudes de todas las subcadenas comunes se suman.
Be aware when using this function, that the order of passing the strings is very important if you want to calculate the percentage of similarity, in fact, altering the variables will give a very different result, example :
<?php
$var_1 = 'PHP IS GREAT';
$var_2 = 'WITH MYSQL';
Recursive algorithm usually is very elegant one. I found a way to get better precision without the recursion. Imagine two different (or same) length ribbons with letters on each. You simply shifting one ribbon to left till it matches the letter the first.
<?php
function similarity($str1, $str2) { $len1 = strlen($str1); $len2 = strlen($str2);
If you have reserved names in a database that you don't want others to use, i find this to work pretty good.
I added strtoupper to the variables to validate typing only. Taking case into consideration will decrease similarity.
<?php
$query = mysql_query("select * from $table") or die("Query failed");
while ($row = mysql_fetch_array($query)) {
similar_text(strtoupper($_POST['name']), strtoupper($row['reserved']), $similarity_pst);
if (number_format($similarity_pst, 0) > 90){
$too_similar = $row['reserved'];
print "The name you entered is too similar the reserved name "".$row['reserved'].""";
break;
}
}
?>
The speed issues for similar_text seem to be only an issue for long sections of text (>20000 chars).
I found a huge performance improvement in my application by just testing if the string to be tested was less than 20000 chars before calling similar_text.
20000+ took 3-5 secs to process, anything else (10000 and below) took a fraction of a second. Fortunately for me, there was only a handful of instances with >20000 chars which I couldn't get a comparison % for.
Well, as mentioned above the speed is O(N^3), i've done a longest common subsequence way that is O(m.n) where m and n are the length of str1 and str2, the result is a percentage and it seems to be exactly the same as similar_text percentage but with better performance... here's the 3 functions i'm using..
function get_lcs($s1, $s2)
{
//ok, now replace all spaces with nothing
$s1 = strtolower(str_lcsfix($s1));
$s2 = strtolower(str_lcsfix($s2));
$lcs = LCS_Length($s1,$s2); //longest common sub sequence
$ms = (strlen($s1) + strlen($s2)) / 2;
return (($lcs*100)/$ms);
}
?>
you can skip calling str_lcsfix if you don't worry about accentuated characters and things like that or you can add up to it or modify it for faster performance, i think ereg is not the fastest way?
hope this helps.
Georges
To calculate the percentage of similarity between two strings without depending on the order of the parameters and be case insensitive, I use this function based on levenshtein's distance:
<?php
// string similarity calculated using levenshtein static function similarity($a, $b) { return 1 - (levenshtein(strtoupper($a), strtoupper($b)) / max(strlen($a), strlen($b))); }
?>
This will always return a number between 0 and 1, representing the percentage, for instance 0.8 represents 80% similar strings.
If you want this to be case-sensitive, just remove the strtoupper() functions.