Relevance of Two Strings

Discussion in 'PHP' started by ketan9, Nov 18, 2006.

  1. #1
    I am looking for something that would give me a comparison relevance of two strings. For eg. If I have string1 and string2, I want to compare them and see how much percentage of these two strings match against one another. Like string1 is apprx 90% equal to string2.

    Something like this is what I am looking for in php. Please help.
     
    ketan9, Nov 18, 2006 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    <?php
    // returns the percentage of the string "similarity"
    function str_compare($str1, $str2) {
       $count = 0;
      
       $str1 = ereg_replace("[^a-z]", ' ', strtolower($str1));
       while(strstr($str1, '  ')) {
           $str1 = str_replace('  ', ' ', $str1);
       }
       $str1 = explode(' ', $str1);
      
       $str2 = ereg_replace("[^a-z]", ' ', strtolower($str2));
       while(strstr($str2, '  ')) {
           $str2 = str_replace('  ', ' ', $str2);
       }
       $str2 = explode(' ', $str2);
      
       if(count($str1)<count($str2)) {
           $tmp = $str1;
           $str1 = $str2;
           $str2 = $tmp;
           unset($tmp);
       }
      
       for($i=0; $i<count($str1); $i++) {
           if(in_array($str1[$i], $str2)) {
               $count++;
           }
       }
      
       return $count/count($str2)*100;
    }
    ?>
    
    PHP:
    Taken from

    http://us2.php.net/similar_text
     
    nico_swd, Nov 18, 2006 IP
  3. crazybjörn

    crazybjörn Peon

    Messages:
    270
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Or you could just use the function itself,

    $i = similar_text($first_word, $second_word, &$p);
    echo("Matched: $i  Percentage: $p%");
    PHP:
     
    crazybjörn, Nov 19, 2006 IP
    ketan9 likes this.
  4. ketan9

    ketan9 Active Member

    Messages:
    548
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    58
    #4
    Thanks, I was not aware of this function. A green rep from me ;)
     
    ketan9, Nov 24, 2006 IP