similar_text

(PHP 4, PHP 5)

similar_textCalculate the similarity between two strings

Description

int similar_text ( string $first , string $second [, float &$percent ] )

This calculates the similarity between two strings as described in Oliver [1993]. Note that this implementation does not use a stack as in Oliver's pseudo code, but recursive calls which may or may not speed up the whole process. Note also that the complexity of this algorithm is O(N**3) where N is the length of the longest string.

Parameters

first

The first string.

second

The second string.

percent

By passing a reference as third argument, similar_text() will calculate the similarity in percent for you.

Return Values

Returns the number of matching chars in both strings.

See Also

  • levenshtein() - Calculate Levenshtein distance between two strings
  • soundex() - Calculate the soundex key of a string

add a note add a note

User Contributed Notes 14 notes

up
63
SPAM HATER
5 years ago
Hey there,

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';

similar_text($var_1, $var_2, $percent);

echo
$percent;
// 27.272727272727

similar_text($var_2, $var_1, $percent);

echo
$percent;
// 18.181818181818
?>
up
58
daniel dot karbach at localhorst dot tv
6 years ago
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

<?php
similar_text
("", "", $sim);
echo
$sim; // "0"
?>
up
9
vasyl at vasyltech dot com
1 year ago
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);
   
   
$max = max($len1, $len2);
   
$similarity = $i = $j = 0;
   
    while ((
$i < $len1) && isset($str2[$j])) {
        if (
$str1[$i] == $str2[$j]) {
           
$similarity++;
           
$i++;
           
$j++;
        } elseif (
$len1 < $len2) {
           
$len1++;
           
$j++;
        } elseif (
$len1 > $len2) {
           
$i++;
           
$len1--;
        } else {
           
$i++;
           
$j++;
        }
    }

    return
round($similarity / $max, 2);
}

$str1 = '12345678901234567890';
$str2 = '12345678991234567890';

echo
'Similarity: ' . (similarity($str1, $str2) * 100) . '%';
?>
up
9
ryan at derokorian dot com
3 years ago
Note that this function is case sensitive:

<?php

$var1
= 'Hello';
$var2 = 'Hello';
$var3 = 'hello';

echo
similar_text($var1, $var2);  // 5
echo similar_text($var1, $var3);  // 4
up
5
Paul
10 years ago
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.
up
4
daniel at reflexionsdesign dot com
15 years ago
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).
up
4
georgesk at hotmail dot com
15 years ago
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..

<?php
function LCS_Length($s1, $s2)
{
 
$m = strlen($s1);
 
$n = strlen($s2);

 
//this table will be used to compute the LCS-Length, only 128 chars per string are considered
 
$LCS_Length_Table = array(array(128),array(128));
 
 
 
//reset the 2 cols in the table
 
for($i=1; $i < $m; $i++) $LCS_Length_Table[$i][0]=0;
  for(
$j=0; $j < $n; $j++) $LCS_Length_Table[0][$j]=0;

  for;      
=1; $i <class="default">strlen<
< $m; $i++) $LCS_Length_Table[$idown
me Rel /> 

Description

int sis
int sis
); 
// 4 ][int sis
); 
sis
ass="methodsynopsis dc-description"> int sis
+"default">$str2
]=int sis
); 
sis
ass="methodsynopsis dc-description"> in] me, Length_Tableint sis
); 
ass="methodsynopsis dc-description"> int sis
int sis
); 
// 4 ][int sis
); 
sis
ass="methodsynopsis dc-description"> in] class="defaultdefaultdefaultbr /
int sis
); 
// 4 ][int sis
); 
// 4 ][ sis
class="defaultdefault}class="default}class="default
    }

&nbpe">int
sis
); ="keyword"><class="default">// 4
[= max= $s2)
 
$n sis
similar_text
, similar_text,
similar_text= $s1  $n sis
similar_text
, similar_text, ""= $s1  $n sis
similar_text
, similar_text, ""= $s1  $n sis
similar_text
, similar_text, ""= $s1  $n sis
similar_text
, similar_text, ""= $s1  $n sis
similar_text
, similar_text, ""= $s1  $n sis
similar_text
, similar_text, ""= $
    }

&nbplss="keyword">=
= max($s1, $s2$s1$len1 = max= max($s1$len2 = max= max, $ss="default">$s1$len2 function LCS_Length(max, $s2); =snbsp;   max= strlen($str2= strlen($similarity (0&;
   
 lcsss="keyword">=
   
&nbsass="keyword">) *
); =sss="keyword">= );&nbs="keyclass="n>s> = $i echo similar_text($s1($s1, similar_text, = );&nbs="keyn>
<115994
up
up
dow5994 0&pa46v>
Actcode>'hello'"t seems; // outpund n 75 be exact <43011
up
up
d43011 0&pa36v>
Scre pLENGHTtext rovement ss than 20000T"php clabg em00 chorthtmlorder otryg simi < siSMALLlculates tml"> Ne. ss thanIishtml simi> ind n 90 is veryllass="k wScre p"fracbbons:. I fvalu/>>s HE) whercorr-lanvalu/>>s HECs than 20000T"e&apmilximbelow)66.7 %, h of stanll udo mi Iind n smes-ing oid=90 %, hlct <42256
up
d42256 0&pa3v>
georgesk at hotmail dot co42256 strong> 9:21a;
3 years 42256 oong>
.erformanIou may w"> If i dgor:rformance... here's the 3 functions i'm using.. echo similar_text($str1($str1, $similarity , = );&nbs="keyclass="n> .e$Buteit'san figurntaguinarhp.ini (es-ow_ to _time_re w_d> r=OOff)rformance... hThst'saitlar_An"fracbgreasshref="/m! :)ly <11681>
oteu">up
up
dow681> 0&paiv>
@I_ cla_9507MER- PAZ! (64% like http://rhp.net/ss="keyword"thi5994 0relan> fos-owhora4" t="_blank">http://rhp.net/ss="keyword"thi5994)ml"> NaoYouhe smost
&s_text class"> I(m.toupuse()/clatolowues , it also dependpan clamuchfospan><"> -las ;p clbe Iishtmn><75% ? Iidoof isee I fvalu/>ay tuchflbr />&s; usspa n sem0br />&s_inspa="phpcodesonsiderably better complexity of O(str1xity of -04 09:00">up img src='/imbges/t&add@2x.png' hlc='lt='a udoe'exadth='12'_teight='12'>iv>mes->lt='a udoensimes->" id="iimilar>