Dark Sterix
Dark Sterix

Reputation: 99

Display best match first

$input = "work is hard";			

if(preg_match(  "/(work|shift|useful)/i",$input)){
$match[]= "this is not better match";
}

if(preg_match(  "/(how|work|can|be|really|really|hard)/i",$input)){
$match[]= "this is better match";   // i want this match to appear first.
}

if i have multiple preg_match and one has more words that match the input, how can i make it so that it displays the one with the most matches. now, it just displays it in order. this is how it outputs

<?php
if(!empty($match)) {
foreach ($match as $r) {
    echo "<li>$r</li>\n";
	
}
}
?>

Upvotes: 1

Views: 73

Answers (2)

Meenakshi
Meenakshi

Reputation: 175

Try this:

$input = "work is hard";            
$reg = array( "First match"=>"/(work|shift|useful)/i","second match"=>"/(how|work|can|be|really|really|hard)/i");
foreach($reg as $index=>$val){
    $count[] = preg_match_all($val,$input);
}
foreach($count as $i){
    $max = max($count);
    $key = array_search($max,$count); 
    $allKeys = array_keys($reg);
    echo "The Best Match is:  ".$allKeys[$key]."<br>"; 
    $del = array_search($max,$count);
    unset($count[$del]);
}

Upvotes: 1

venkatKA
venkatKA

Reputation: 2399

split the input string into an array of words and use array_intersect with your sets of words of interest and compare the lengths of the resulting arrays to decide the best match.

Upvotes: 0

Related Questions