php - 反向搜索全文/类似脏搜索词
问题描述
我有一个关于针对数据库搜索字符串的小问题。
想象一下这种情况。我有一张包含所有汽车品牌和型号的表格,类似于以下内容:
+---------------------------+-------------------+
| name | alternative_names |
+---------------------------+-------------------+
| Peugeot 207 | |
| Peugeot 208 | |
| Peugeot 308 | |
| Peugeot 308 Station Wagon | estate sw |
| Peugeot 307 | |
+---------------------------+-------------------+
我需要从大多数时候都是脏的字符串开始识别保存在数据库中的汽车。
“标致 308”应该返回标致 308
“标致308旅行车”应该返回标致308旅行车
“自动标致308”应该返回标致308
“sw peugeot 308”应该返回Peugeot 308 Station Wagon
知道我应该如何处理和解决这个问题吗?
解决方案
很难预见所有可能的脏词,所以最好在 PHP 中创建帮助器,什么会用大写首字母生成单词并替换单词sw
喜欢Station Wagon
function modelNormalizer($model)
{
$possible_replace = [
'sw' => 'Station Wagon',
];
$byWord = explode(' ', $model);
foreach ($byWord as $i => $word) {
foreach ($possible_replace as $from => $to) {
$byWord[$i] = ucfirst(strtolower(str_replace($from, $to, $word)));
}
}
return implode(' ', $byWord);
}
您还可以对 DB 中的数据进行规范化,例如将单词从前移动peugeot
到末尾。
SELECT
CONCAT(SUBSTR(t.name, LOCATE('peugeot 308', t.name)), ' ', SUBSTR(t.name, 1, LOCATE('peugeot 308', t.name)-1)) AS model
FROM yourtable AS t
WHERE t.name like "%peugeot 308%" #WARNING YOUR INDEX WILL NOT WORK WITH % PREFIX
推荐阅读
- ios - 构建失败 xcode 10 错误:使用 Cocoapods 找不到架构 x86_64 的符号(带有屏幕和配置)
- excel - VBA、电子邮件、ActiveX 组件无法创建对象
- android - 解析服务器如何在 logInWithInBackground 后获取 AuthenticationCallback?
- javascript - 使用表单上传excel文件后如何获取excel工作表的名称
- javascript - 如何将媒体查询放入 javascript
- haskell - Haskell中Either和Except在用法上有什么区别?
- python - 格式化命令行字符串的代码约定是什么?
- r - 检查每组一个df是否至少有两个值与另一组匹配
- ios - Firebase 通知未在 iOS 上播放声音
- r - 导入 csv 并用闪亮的仪表板编写它们