我需要始终从我的数据库中获取尽可能长的匹配项。
MyDatabase ( id/phrase )
1: '我'
2: '开始'
3: '我去上学'
4: '与'
5: '和我的狗 Gogo'
6: '日'
7: '每一天'
8: '除了'
9: '周末除外'
10:'周末'
用户输入 = 'AwordThatsNOTinDB 我每天都和我的狗 Gogo 一起去学校 AwordThatsNOTinDB,周末除外 AwordThatsNOTinDB'
因此,当用户输入上述内容时,我想从数据库中按此顺序以数组形式获取以下 ID:
大批(
“未找到”,
3、
“未找到”,
5, 7, 9,
“未找到”);
最佳答案
我会使用这个解决方案:
1- 从数据库中按字符串长度顺序选择所有字符串。
2- 遍历我的数据库字符串并在用户输入中替换它们。如果字符串发生变化,我会更新原始字符串,并将我所在的字符串的 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);
关于php - mysql php查询查找输入的最长匹配部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27124779/