note 118799 added to function.similar-text
| From: | vasyl at vasyltech dot com | Date: | Mon, 08 Feb 2016 14:15:05 +0000 |
| Subject: | note 118799 added to function.similar-text | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204896@lists.php.net to get a copy of this message | ||
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) . '%';
?>
----
Server IP: 72.52.91.14
Probable Submitter: 24.172.70.250
----
Manual Page -- http://php.net/manual/en/function.similar-text.php
Edit -- https://master.php.net/note/edit/118799
Del: integrated -- https://master.php.net/note/delete/118799/integrated
Del: useless -- https://master.php.net/note/delete/118799/useless
Del: bad code -- https://master.php.net/note/delete/118799/bad+code
Del: spam -- https://master.php.net/note/delete/118799/spam
Del: non-english -- https://master.php.net/note/delete/118799/non-english
Del: in docs -- https://master.php.net/note/delete/118799/in+docs
Del: other reasons-- https://master.php.net/note/delete/118799
Reject -- https://master.php.net/note/reject/118799
Search -- https://master.php.net/manage/user-notes.php