php - mysql php查询查找输入的最长匹配部分

标签 php mysql

我需要始终从我的数据库中获取尽可能长的匹配项。

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/

相关文章:

php - MySQL 服务器版本与 PHP 报告的 MySQL 版本不同

php - 如何将多维集合(数组)展平为宏(Laravel)中的点符号版本?

php - Warning : fread() [function. fread]: Length参数必须大于0

mysql - Laravel Schema Builder 改变存储引擎

mysql - 使用 join codeigniter 同时删除两个 mysql 表

php - 检查 ids 列表是否都存在于 MySQL 和 PHP 中

php - 下个月,PHP 的同一天

mysql - Rails 关联有两个外键?

php - 显示一次父表标题字段,然后显示组中的子记录

php - 如何修复 PHP MySQL 中达到 508 资源限制