PHP.mk документација

similar_text

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.similar-text.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.similar-text.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
similar_text

Референца за `function.similar-text.php` со подобрена типографија и навигација.

function.similar-text.php

similar_text

(PHP 4, PHP 5, PHP 7, PHP 8)

similar_textПресметај ја сличноста помеѓу два низа

= NULL

similar_text(string $string1, string $string2, float &$percent = null): int

Ова го пресметува односот на сличност помеѓу два низа како што е опишано во Programming Classics: Implementing the World's Best Algorithms од Oliver (ISBN 0-131-00413-1). Имајте предвид дека оваа имплементација не користи стек како во псевдо-кодот на Oliver, туку рекурзивни повици кои можеби ќе го забрзаат или нема да го забрзаат целиот процес. Исто така, имајте предвид дека сложеноста на овој алгоритам е O(N**3) каде N е должината на најдолгиот низ.

Параметри

string1

Првата низа.

string2

Втората низа.

Забелешка:

Заменувањето на string1 and string2 може да даде различен резултат; видете го примерот подолу.

percent

Со поминување на референца како трет аргумент, similar_text() ќе ја пресмета сличноста во проценти, со делење на резултатот од similar_text() со просекот на должините на дадените низови пати 100.

Вратени вредности

Враќа број на совпаѓачки знаци во двата низа.

Бројот на совпаѓачки знаци се пресметува со наоѓање на најдолгиот прв заеднички подниз, а потоа со рекурзивно правење на истото за префиксите и суфиксите. Се собираат должините на сите пронајдени заеднички поднизови.

Примери

Пример #1 similar_text() пример за замена на аргументи

Овој пример покажува дека заменувањето на string1 and string2 аргументот може да даде различни резултати.

<?php
$sim
= similar_text('bafoobar', 'barfoo', $perc);
echo
"similarity: $sim ($perc %)\n";
$sim = similar_text('barfoo', 'bafoobar', $perc);
echo
"similarity: $sim ($perc %)\n";

Горниот пример ќе прикаже нешто слично на:

similarity: 5 (71.428571428571 %)
similarity: 3 (42.857142857143 %)

Види Исто така

  • levenshtein() - Пресметај ја Левитенштајновата далечина помеѓу два низи
  • metaphone() - Пресметај го метафонскиот клуч на низа
  • soundex() - Пресметај го саундексот на низа

Белешки од корисници 11 белешки

SPAM HATER
пред 13 години
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
?>
daniel dot karbach at localhorst dot tv
пред 15 години
Please note that this function calculates a similarity of 0 (zero) for two empty strings.

<?php
similar_text("", "", $sim);
echo $sim; // "0"
?>
I_HATE_SPAMMER- PAZ!
пред 11 години
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
vasyl at vasyltech dot com
пред 10 години
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) . '%';
?>
ryan на derokorian точка com
12 години пред
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
daniel at reflexionsdesign dot com
figroc at gmail dot com
If performance is an issue, you may wish to use the levenshtein() function instead, which has a considerably better complexity of O(str1 * str2).
julius at infoguiden dot no
пред 23 години
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 &quot;".$row['reserved']."&quot;";
        break;
       }
    }
?>
Анонимен
пред 5 години
$result = similar_text ('ab', 'a', $percent);

> $percent: 66.666666666666671
Пол
19 години пред
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.
georgesk at hotmail dot com
figroc at gmail dot com
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
pablo dot pazos at cabolabs dot com
пред 5 години
To calculate the percentage of similarity between two strings without depending on the order of the parameters and be case insensitive, I use this function based on levenshtein's distance:

<?php

  // string similarity calculated using levenshtein
  static function similarity($a, $b)
  {
    return 1 - (levenshtein(strtoupper($a), strtoupper($b)) / max(strlen($a), strlen($b)));
  }

?>

This will always return a number between 0 and 1, representing the percentage, for instance 0.8 represents 80% similar strings.

If you want this to be case-sensitive, just remove the strtoupper() functions.
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.