【问题标题】:Highlight function highlights words in words高亮功能高亮单词中的单词
【发布时间】:2015-05-13 01:00:20
【问题描述】:

我开发了以下功能来突出显示搜索结果名称。

function highlight($text, $words)
    {
        if (!is_array($words))
        {
            $words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
        }

        $regex = '#\\b(\\w*)(';
        $sep = '';
        foreach ($words as $word)
        {
            $regex .= $sep . preg_quote($word, '#');
            $sep = '|';
        }
        $regex .= ')(\\w*)\\b#i';

        $text = preg_replace($regex, '\\1<b>\\2</b>\\3', $text);
        $text = str_replace("</b> <b>"," ",$text);
        return $text;
    }

我的问题是,如果文本是“This is the end” 我正在寻找“this is”,它会像这样突出显示:“this is the end”,因为“is”这个词也在“this”中。

有人知道如何解决这个问题吗?

我的第一个想法是只替换 whitespace[whitespace] 但这不是一个好的解决方案,因为句子中的第一个单词在开头没有空格。 :-(

感谢您的帮助。

【问题讨论】:

    标签: php regex highlight


    【解决方案1】:

    从正则表达式的开头和结尾删除\w*

        $regex = '#\\b(';
        $sep = '';
        foreach ($words as $word)
        {
            $regex .= $sep . preg_quote($word, '#');
            $sep = '|';
        }
        $regex .= ')\\b#i';
    
        $text = preg_replace($regex, '<b>$1</b>', $text);
    

    【讨论】:

    • 突出显示空格 cO:“This is The end” 编辑:抱歉,我没有看到 preg_replace 的变化。 :-) 解决了 - 非常感谢
    • @Marv:保留你的str_replace
    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2012-03-24
    • 2011-05-20
    • 1970-01-01
    • 2014-07-13
    • 2023-03-13
    相关资源
    最近更新 更多