From 5d4baf438314931832c6cef226117946b798d55d Mon Sep 17 00:00:00 2001 From: jsasg <735273025@qq.com> Date: Wed, 2 Jul 2025 10:58:53 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20=E5=85=B3=E9=94=AE=E8=AF=8D=E9=AB=98?= =?UTF-8?q?=E4=BA=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/index/common.php | 18 +++++++++--------- app/index/controller/Product.php | 7 ++++--- 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/app/index/common.php b/app/index/common.php index 81d3df13..63d2a364 100644 --- a/app/index/common.php +++ b/app/index/common.php @@ -226,18 +226,18 @@ if (!function_exists('get_platform')) { if (!function_exists('highlight_keywords')) { /** * 高亮关键词 - * @param string $item - * @param string $keywords - * @param array $class + * @param string $text // 要处理的文本 + * @param string $keyword // 关键词 + * @param string|callable $repalce // 替换函数或字符串 * @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) { - if (empty($match)) { - return $text; - } - return '' . $match[0] . ''; + return preg_replace_callback('/' . preg_quote($keyword, '/') . '+/i', function($match) use($text, $replace) { + if (empty($match)) return $text; + if (is_string($replace)) return '' . $match[0] . ''; + if (is_callable($replace)) return $replace($match[0]); + return $match[0]; }, $text); } } diff --git a/app/index/controller/Product.php b/app/index/controller/Product.php index b16ded89..1dcd0921 100644 --- a/app/index/controller/Product.php +++ b/app/index/controller/Product.php @@ -299,9 +299,10 @@ class Product extends Common 'query' => request()->param() ]) ->each(function ($item) use($keywords) { - $item['spu'] = highlight_keywords($item['spu'], $keywords, ['redpoint']); - $item['name'] = highlight_keywords($item['name'], $keywords, ['redpoint']); - $item['short_name'] = highlight_keywords($item['short_name'], $keywords, ['redpoint']); + $replace = fn($txt) => '' . $txt . ''; + $item['spu'] = highlight_keywords($item['spu'], $keywords, $replace); + $item['name'] = highlight_keywords($item['name'], $keywords, $replace); + $item['short_name'] = highlight_keywords($item['short_name'], $keywords, $replace); return $item; }); View::assign('products', $products);