fix: 产品搜索关键词高亮
This commit is contained in:
@@ -222,3 +222,22 @@ if (!function_exists('get_platform')) {
|
|||||||
return $platform;
|
return $platform;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!function_exists('highlight_keywords')) {
|
||||||
|
/**
|
||||||
|
* 高亮关键词
|
||||||
|
* @param string $item
|
||||||
|
* @param string $keywords
|
||||||
|
* @param array $class
|
||||||
|
* @return string
|
||||||
|
*/
|
||||||
|
function highlight_keywords(string $text, string $keywords, array $class=[]): string
|
||||||
|
{
|
||||||
|
return preg_replace_callback('/' . preg_quote($keywords, '/') . '+/i', function($match) use($text, $class) {
|
||||||
|
if (empty($match)) {
|
||||||
|
return $text;
|
||||||
|
}
|
||||||
|
return '<strong class="' . implode(' ', $class) . '">' . $match[0] . '</strong>';
|
||||||
|
}, $text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -299,9 +299,9 @@ class Product extends Common
|
|||||||
'query' => request()->param()
|
'query' => request()->param()
|
||||||
])
|
])
|
||||||
->each(function ($item) use($keywords) {
|
->each(function ($item) use($keywords) {
|
||||||
$item['spu'] = str_replace($keywords, '<strong class="redpoint">'.$keywords.'</strong>', $item['spu']);
|
$item['spu'] = highlight_keywords($item['spu'], $keywords, ['redpoint']);
|
||||||
$item['name'] = str_replace($keywords, '<strong class="redpoint">'.$keywords.'</strong>', $item['name']);
|
$item['name'] = highlight_keywords($item['name'], $keywords, ['redpoint']);
|
||||||
$item['short_name'] = str_replace($keywords, '<strong class="redpoint">'.$keywords.'</strong>', $item['short_name']);
|
$item['short_name'] = highlight_keywords($item['short_name'], $keywords, ['redpoint']);
|
||||||
return $item;
|
return $item;
|
||||||
});
|
});
|
||||||
View::assign('products', $products);
|
View::assign('products', $products);
|
||||||
|
|||||||
@@ -79,6 +79,6 @@ class ProductModel extends ProductBaseModel
|
|||||||
// 关键词搜索
|
// 关键词搜索
|
||||||
public function searchKeywordsAttr($query, string $keywords)
|
public function searchKeywordsAttr($query, string $keywords)
|
||||||
{
|
{
|
||||||
$query->whereRaw('BINARY spu LIKE "%' . $keywords . '%" OR BINARY name LIKE "%' . $keywords . '%" OR BINARY short_name LIKE "%' . $keywords . '%"');
|
$query->whereRaw('spu LIKE "%' . $keywords . '%" OR name LIKE "%' . $keywords . '%" OR short_name LIKE "%' . $keywords . '%"');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user