首先显示最佳匹配
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.
}
如果我有多个 preg_match 并且其中有多个单词与输入匹配,我如何才能让它显示匹配最多的单词。现在,它只是按顺序显示它。这是它的输出方式
<?php
if(!empty($match)) {
foreach ($match as $r) {
echo "<li>$r</li>\n";
}
}
?>
将输入字符串拆分为一个单词数组,然后将 array_intersect
与您感兴趣的单词集一起使用,然后比较生成的数组的长度以确定最佳匹配。
试试这个:
$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]);
}
$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.
}
如果我有多个 preg_match 并且其中有多个单词与输入匹配,我如何才能让它显示匹配最多的单词。现在,它只是按顺序显示它。这是它的输出方式
<?php
if(!empty($match)) {
foreach ($match as $r) {
echo "<li>$r</li>\n";
}
}
?>
将输入字符串拆分为一个单词数组,然后将 array_intersect
与您感兴趣的单词集一起使用,然后比较生成的数组的长度以确定最佳匹配。
试试这个:
$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]);
}