全球主机交流论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

IP归属甄别会员请立即修改密码
查看: 340|回复: 3
打印 上一主题 下一主题

[已解决]求一个php关键词标红的算法!

[复制链接]
跳转到指定楼层
1#
发表于 2023-2-8 14:28:57 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 zhongziso 于 2023-2-8 14:57 编辑

比如搜索关键词:cctv。搜索结果中的cctv不论大小写都标红,但是不能改变原来的结果。不能把结果中的CCTV替换成小写了。或者小写替换成大写,也不能拆分,不能把c,t,v这几个字符标红,必须是整体cctv才行。

改进后的算法如下:


感谢大佬@enjoyit
2#
发表于 2023-2-8 14:38:45 | 只看该作者

function high light_keywords($text, $keyword) {
    $keyword = preg_quo te($keyword);
    return preg_re place("/\b($keyword)\b/i", '<span style="color:red;">$1</span>', $text);
}
3#
发表于 2023-2-8 14:47:05 | 只看该作者

function highlightKeyword($text, $keyword) {
    $keywordLower = strtolower($keyword);
    $textLower = strtolower($text);
    $pos = strpos($textLower, $keywordLower);

    while ($pos !== false) {
        $start = substr($text, 0, $pos);
        $end = substr($text, $pos + strlen($keyword));
        $text = $start . "<mark>" . substr($text, $pos, strlen($keyword)) . "</mark>" . $end;
        $textLower = strtolower($text);
        $pos = strpos($textLower, $keywordLower);
    }

    return $text;
}

$searchTerm = 'cctv';
$text = 'This is an example text where the keyword CCTV is found.';
$highlightedText = highlightKeyword($text, $searchTerm);
echo $highlightedText;
4#
 楼主| 发表于 2023-2-8 14:48:57 | 只看该作者
enjoyit 发表于 2023-2-8 14:38
function high light_keywords($text, $keyword) {
    $keyword = preg_quo te($keyword);
    return pr ...

感谢大佬
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|全球主机交流论坛

GMT+8, 2025-10-31 20:30 , Processed in 0.059073 second(s), 10 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表