Please note that this function calculates a similarity of 0 (zero) for two empty strings.
<?php
similar_text("", "", $sim);
echo $sim; // "0"
?>
similar_text
(PHP 4, PHP 5)
similar_text — 두 문자열 사이의 유사성을 계산
설명
int similar_text
( string $first
, string $second
[, float &$percent
] )
Oliver[1993]에 설명된 대로 두 문자열의 유사성을 계산합니다. 이 구현은 Oliver의 모의 코드처럼 스택은 아니지만, 재귀 호출이므로 처리의 전체 속도에 영향을 줄 수 있습니다. 이 알고리즘의 복잡도는, N이 가장 긴 문자열일 때 O(N**3)입니다.
인수
- first
-
첫번째 문자열.
- second
-
두번째 문자열.
- percent
-
세번째 인수를 참조로 전달하면, similar_text()는 유사성 퍼센트를 계산합니다.
반환값
두 문자열에서 매치한 문자 수를 반환합니다.
참고
- levenshtein() - Calculate Levenshtein distance between two strings
- soundex() - 문자열의 soundex 키를 계산
daniel dot karbach at localhorst dot tv ¶
2 years ago
SPAM HATER ¶
10 months 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
?>
Paul ¶
6 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.
hate at spam dot com dot BR ¶
9 years ago
In PHP4+, you don't need to pass the percent variable as reference..
Instead, use this way:
<?php
similar_text($string1, $string2, $p);
echo "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! :)
romain dot boyer at gmail dot com ¶
5 years ago
Like levenchtein(), You can do :
(strlen($string2) - similar_text($string,$string2))
to see how much characters have been changed.
julius at infoguiden dot no ¶
10 years ago
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;
}
}
?>
georgesk at hotmail dot com ¶
11 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 ($i=1; $i <= $m; $i++) {
for ($j=1; $j <= $n; $j++) {
if ($s1[$i-1]==$s2[$j-1])
$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];
else
$LCS_Length_Table[$i][$j] = $LCS_Length_Table[$i][$j-1];
}
}
return $LCS_Length_Table[$m][$n];
}
function str_lcsfix($s)
{
$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);
return $s;
}
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
daniel at reflexionsdesign dot com ¶
11 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).
louis #at# mulliemedia.com ¶
8 years ago
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 :
e.g.
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.
mogmios at hushmail dot com ¶
13 years ago
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.
<?php
$i = similar_text($first_word, $second_word, &$p);
echo("Matched: $i Percentage: $p%");
?>
