搜索實(shí)現(xiàn)分詞搜索功能
實(shí)現(xiàn)原理:
如 “裝修二級(jí)” 拆分為 “裝”“修”“二”“級(jí)”,只要目標(biāo)內(nèi)容包含這幾個(gè)字即可匹配,無(wú)需考慮順序和同義詞。
找到搜索文件 /dayrui/App/Module/Models/Search.php
大約187行 注釋掉下面這個(gè)代碼
// 關(guān)鍵字匹配條件
if ($param['keyword'] != '') {
$temp = [];
$sfield = explode(',', $this->module['setting']['search']['field'] ? $this->module['setting']['search']['field'] : 'title,keywords');
$search_keyword = explode('|', addslashes((string)$param['keyword']));
foreach ($search_keyword as $kw) {
$is = 0;
if ($sfield) {
foreach ($sfield as $t) {
if ($t && dr_in_array($t, $field)) {
$is = 1;
$temp[] = $this->module['setting']['search']['complete'] ? '`'.$table.'`.`'.$t.'` = \''.$kw.'\'' : '`'.$table.'`.`'.$t.'` LIKE \'%'.$kw.'%\'';
}
}
}
if (!$is) {
$temp[] = $this->module['setting']['search']['complete'] ? '`'.$table.'`.`title` = \''.$kw.'\'' : '`'.$table.'`.`title` LIKE \'%'.$kw.'%\'';
}
}
$where['keyword'] = $temp ? '('.implode(' OR ', $temp).')' : '';
$param_new['keyword'] = $search_keyword;
}然后下面增加
// 關(guān)鍵字匹配條件(分詞搜索:拆分單個(gè)字符,匹配所有字符)
if ($param['keyword'] != '') {
$temp = [];
$sfield = explode(',', $this->module['setting']['search']['field'] ? $this->module['setting']['search']['field'] : 'title,keywords');
$original_kw = addslashes((string)$param['keyword']);
// 拆分關(guān)鍵詞為單個(gè)字符(支持漢字)
$chars = [];
$length = mb_strlen($original_kw, 'UTF-8');
for ($i = 0; $i < $length; $i++) {
$char = mb_substr($original_kw, $i, 1, 'UTF-8');
// 過(guò)濾空字符和特殊符號(hào)
if ($char && preg_match('/[\p{Han}\d]/u', $char)) {
$chars[] = $char;
}
}
// 如果有有效字符則構(gòu)建條件
if (!empty($chars)) {
foreach ($chars as $char) {
$char_conditions = [];
// 對(duì)每個(gè)搜索字段添加包含當(dāng)前字符的條件
if ($sfield) {
foreach ($sfield as $t) {
if ($t && dr_in_array($t, $field)) {
$char_conditions[] = '`'.$table.'`.`'.$t.'` LIKE \'%'.$char.'%\'';
}
}
}
// 如果沒(méi)有指定字段,默認(rèn)用title
if (empty($char_conditions)) {
$char_conditions[] = '`'.$table.'`.`title` LIKE \'%'.$char.'%\'';
}
// 每個(gè)字符必須至少匹配一個(gè)字段(用OR連接字段,用AND連接不同字符)
$temp[] = '('.implode(' OR ', $char_conditions).')';
}
// 所有字符條件用AND連接(必須包含所有字符)
$where['keyword'] = $temp ? '('.implode(' AND ', $temp).')' : '';
}
$param_new['keyword'] = $original_kw;
}既可以實(shí)現(xiàn)分詞搜索。