PHP - similar_text
Trieda
Metóda - similar_text
(PHP 4, PHP 5, PHP 7)
The function calculates the similarity between two strings using the
algorithm from World's Best Algorithms by Oliver. The implementation uses a
recursion instead of the stack. The algorithm's time comlexity is
O(n3) where n is the length of the longer string.
Procedurálne
- function similar_text (string $first, string $second, float &$percent) : int
Parametre
| Názov | Dátový typ | Predvolená hodnota | Popis |
|---|---|---|---|
| $first | string | The first string we want to compare. | |
| $second | string | The second string we want to compare. | |
| &$percent | float | A variable passed by reference for storing the similarity expressed in percentage. |
Mávratovej hodnoty
Vracia: int
The function returns the number of matching characters of both strings.
Príklady
In the example below we compare two different strings and the percentage
similarity is stored into the $percent variable .
<?php
$text1 = "Chuck Norris knows if Schrödinger's cat is alive or death.";
$text2 = "The only time Chuck Norris was wrong was when he thought he had made a mistake.";
echo similar_text($text1, $text2, $percent) . "<br>";
echo $percent . "<br>";
// The result also depends on the order of the strings.
echo similar_text($text2, $text1, $percent) . "<br>";
echo $percent . "<br>";
// The function can be very useful for searching.
$text3 = "Chuck Norris";
$text4 = "Chuck Noris";
echo similar_text($text3, $text4, $percent) . "<br>";
echo $percent . "<br>";
// The result of two empty strings is 0 (0%).
echo similar_text("", "", $percent) . "<br>";
echo $percent . "<br>";
// If the strings are same (not empty), the result is 1 (100%);
echo similar_text(" ", " ", $percent) . "<br>";
echo $percent . "<br>";
Súvisiace manuály
- function levenshtein (string $str1, string $str2, int $cost_ins, int $cost_rep, int $cost_del) : int
