(PHP 4, PHP 5)

similar_textВычисляет степень похожести двух строк


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

Вычисляет степень похожести двух строк по алгоритму, описанному Oliver [1993]. Эта реализация алгоритма не использует стека, использованного в оригинале, вместо этого применяются рекурсивные вызовы, что в некоторых случаях может ускорить процесс. Сложность алгоритма составляет O(N**3), где N - длина более длинной из двух строк.

Список параметров


Первая строка.


Вторая строка.


При передаче по ссылке третьего аргумента, similar_text() присваивоит ему степень похожести двух строк в процентах.

Возвращаемые значения

Возвращается количество совпадающих символов в двух строках.

Смотрите также

  • levenshtein() - Вычисляет расстояние Левенштейна между двумя строками
  • soundex() - Возвращает ключ soundex для строки


Don't forget your passing the double as a reference. If you use this and soundex() together you can get a pretty good guess as to how well two words match. Is useful for simple bot-like programs.

similar_text($first_word$second_word, &$p);
"Matched: $i  Percentage: $p%");
2000-02-01 19:39:54
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).
2001-10-09 21:30:24
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 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;
$j=0$j $n$j++) $LCS_Length_Table[0][$j]=0;

  for (
$i=1$i <= $m$i++) {
    for (
$j=1$j <= $n$j++) {
      if (
$LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j-1] + 1;
      else if (
$LCS_Length_Table[$i-1][$j] >= $LCS_Length_Table[$i][$j-1])
$LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i-1][$j];
$LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i][$j-1];

$s str_replace(" ","",$s);
$s ereg_replace("[��������]","e"$s);
$s ereg_replace("[������������]","a"$s);
$s ereg_replace("[��������]","i"$s);
$s ereg_replace("[���������]","o"$s);
$s ereg_replace("[��������]","u"$s);
$s ereg_replace("[�]","c"$s);
//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 ((

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.
2002-03-08 22:14:41
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. 

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_pst0) > 90){
$too_similar $row['reserved'];
"The name you entered is too similar the reserved name &quot;".$row['reserved']."&quot;";
2003-02-06 08:46:37
In PHP4+, you don't need to pass the percent variable as reference..
Instead, use this way:

"Percent: $p%";

In PHP5, you'll get a ugly warning message when passing this variable as reference.. But it's configurable in php.ini (allow_call_time_pass_reference = Off)

That's it... Another great function! :)
2004-05-10 00:21:23
Note that this function will calculate the percentage blindly, without regard to the LENGHT of the string.

This may become important if you try to print similar names to SMALL strings :
I want to print out the value if it is 90 percent similar to the other one : the value is HE, the correct value is HEC

The similar_text() function will return approximately 66.7 %, and it will not print it because it is smaller than 90 %, although almost all of the string was matched.
2004-06-06 20:01:07
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.
2007-01-18 22:50:06
Like levenchtein(), You can do :

(strlen($string2) - similar_text($string,$string2))

to see how much characters have been changed.
2007-08-08 08:59:30
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

$sim// "0"
2010-12-17 08:48:52
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 :

$var_2 'WITH MYSQL';


// 27.272727272727


// 18.181818181818
2012-07-23 21:16:06
Note that this function is case sensitive:


$var2 'Hello';
$var3 'hello';

similar_text($var1$var2);  // 5
echo similar_text($var1$var3);  // 4
2014-03-04 23:00:42
Actually similar_text() is not bad...
it works good. But before processing i think is a good way to make a little mod like this

$var_1 = strtoupper("doggy");
$var_2 = strtoupper("Dog");

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

echo $percent; // output is 75 but without strtoupper output is 50
2014-10-24 12:59:20
Not only will your code fail the "turkey test" (google it), and for a matter most comments here that use strtoupper()/strtolower(), it also depends very much on the use-case; maybe I wanted the 75% ? I don't see the value of such comments; this is something everybody could've come op with. It's basic programming and turning requirements into algorithms.
2015-03-04 15:39:44
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.


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]) {
        } elseif (
$len1 $len2) {
        } elseif (
$len1 $len2) {
        } else {

round($similarity $max2);

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

'Similarity: ' . (similarity($str1$str2) * 100) . '%';
2016-02-08 16:15:03

    Поддержать сайт на родительском проекте КГБ