Search code examples
phppreg-match

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";
	
}
}
?>


Solution

  • 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]);
    }