perf: 关键词高亮

This commit is contained in:
2025-07-02 10:58:53 +08:00
parent 326ea8ae7e
commit aba102d63c
2 changed files with 13 additions and 12 deletions

View File

@@ -226,18 +226,18 @@ if (!function_exists('get_platform')) {
if (!function_exists('highlight_keywords')) { if (!function_exists('highlight_keywords')) {
/** /**
* 高亮关键词 * 高亮关键词
* @param string $item * @param string $text // 要处理的文本
* @param string $keywords * @param string $keyword // 关键词
* @param array $class * @param string|callable $repalce // 替换函数或字符串
* @return string * @return string
*/ */
function highlight_keywords(string $text, string $keywords, array $class=[]): string function highlight_keywords(string $text, string $keyword, string|callable $replace): string
{ {
return preg_replace_callback('/' . preg_quote($keywords, '/') . '+/i', function($match) use($text, $class) { return preg_replace_callback('/' . preg_quote($keyword, '/') . '+/i', function($match) use($text, $replace) {
if (empty($match)) { if (empty($match)) return $text;
return $text; if (is_string($replace)) return '<strong>' . $match[0] . '</strong>';
} if (is_callable($replace)) return $replace($match[0]);
return '<strong class="' . implode(' ', $class) . '">' . $match[0] . '</strong>'; return $match[0];
}, $text); }, $text);
} }
} }

View File

@@ -299,9 +299,10 @@ class Product extends Common
'query' => request()->param() 'query' => request()->param()
]) ])
->each(function ($item) use($keywords) { ->each(function ($item) use($keywords) {
$item['spu'] = highlight_keywords($item['spu'], $keywords, ['redpoint']); $replace = fn($txt) => '<strong class="redpoint">' . $txt . '</strong>';
$item['name'] = highlight_keywords($item['name'], $keywords, ['redpoint']); $item['spu'] = highlight_keywords($item['spu'], $keywords, $replace);
$item['short_name'] = highlight_keywords($item['short_name'], $keywords, ['redpoint']); $item['name'] = highlight_keywords($item['name'], $keywords, $replace);
$item['short_name'] = highlight_keywords($item['short_name'], $keywords, $replace);
return $item; return $item;
}); });
View::assign('products', $products); View::assign('products', $products);