Muzaffer
Muzaffer

Reputation: 306

PHP : Compare two sentence

I need to compare below two sentences and the output should be percentage of matching

A: senior manager, production

B: senior manager, prodcution-sales

I tried by comparing each word of the sentence (code below). it works but i need much efficient way.

public function contact_title_match($old_title,$new_title)
{
   $new_title=preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $new_title);
   $new_title_arr=explode(" ",$new_title);
   $count=count($new_title_arr);
   $index=0;
   if($count>0)
   {
      foreach($new_title_arr as $title_word)
      {
        if(stripos($old_title,$title_word)!==false)
            $index++;
      }
      if(($index/$count)>= 0.5) return 1;
      else                      return 0;
   }
}

Upvotes: 0

Views: 2947

Answers (1)

Sampson
Sampson

Reputation: 268364

Sounds like a good job for similar_text:

$sentence_a = "senior manager, production";
$sentence_b = "senior manager, prodcution-sales";
$percentage = 0;

similar_text( $sentence_a, $sentence_b, $percentage );

// The strings are 86 percent similar.
printf("The strings are %d percent similar.", $percentage);

Demo: http://codepad.org/9Vx797uB

Upvotes: 8

Related Questions