我需要始终从我的数据库获得最长的匹配。
MyDatabase (id /词组)
1:'我'
2:'去'
3:'我去学校'
4:''
5:'我的狗名叫Gogo'
6:' day'
7:'每天'
8:'除了'
9:'除了周末'
10:'周末'
用户输入 =' AwordThatsNOTinDB每天我和我的狗Gogo上学AwordThatsNOTinDB,除了周末AwordThatsNOTinDB'
因此,当用户输入上述内容时,我希望从数据库中按顺序获取以下ID作为数组:
阵列(
"没发现的&#34 ;,
3,
"没发现的&#34 ;,
5,7,9,
"没发现的&#34);
答案 0 :(得分:1)
我会使用这个解决方案:
1-按字符串的长度从数据库顺序中选择所有字符串。
2-循环遍历我的db字符串并在用户输入中替换它们。如果字符串更改我更新了oringal字符串,并将我所在的字符串的id添加到找到的数组中。
$found_phrase=array();
$string=strtolower('AwordThatsNOTinDB I go to school AwordThatsNOTinDB with my dog named Gogo every day except weekends AwordThatsNOTinDB');
// LIMIT DB-SEARCH
$string=preg_replace('!\s+!', ' ', $string); // replace multiple spaces with one space
$where=explode(" ",$string);
foreach($where as $whereVal){
$whereQuery=$whereQuery." phrase LIKE '%".$whereVal."%' OR";
}
$whereQuery=rtrim($whereQuery,"OR"); // delete last OR
$whereQuery="WHERE ".$whereQuery." ";
$query=$conn->prepare("SELECT id, phrase FROM table $whereQuery ORDER BY length(phrase) DESC");
$query->execute();
while($array=$query->fetch(PDO::FETCH_ASSOC)){
$new_string=str_replace(strtolower($array['phrase']), "[{$array['id']}]", $string);
if($new_string!=$string){
$string=$new_string;
}
}
$string=preg_replace('/([A-Z0-9,.]){1,} /i', ' Not-Found ', $string);
$string=preg_replace('/\[([0-9])*\]/i', str_replace(array('[',']'), '',"$1"), $string);
$string_array=explode(' ', $string);
print_r($string_array);
答案 1 :(得分:0)
请从数据库中获取此数组
$phrases=array(
'1'=> 'I',
'2'=> 'go',
'3'=> 'I go to school',
'4'=> 'with',
'5'=> 'with my dog named Gogo',
'6'=> 'day',
'7'=> 'every day',
'8'=> 'except',
'9'=> 'except weekends',
'10'=>'weekends'
);
$user_input = 'AwordThatsNOTinDB I go to school AwordThatsNOTinDB with my dog named Gogo every day except weekends AwordThatsNOTinDB';
$matches=array();
foreach($phrases as $id=>$phrase){
$x=false;
if(strpos($user_input,$phrase)!==false){
if(!empty($matches)){
foreach($matches as $key=>$match){
if((strpos($phrase,$match)!==false) && $phrase !== $match)
unset($matches[$key]);
if((strpos($match,$phrase)!==false)){
$x = true;
break;
}
}
}
if(!$x)
$matches[$id]=$phrase;
}
}
var_dump($matches);
?>