【问题标题】:highlighting words at the end of a word在单词末尾突出显示单词
【发布时间】:2011-02-25 07:00:51
【问题描述】:

我不确定如何更好地表达标题,但我的问题是突出显示功能不会突出显示单词末尾的搜索关键字。例如,如果搜索关键字是“self”,它会突出“self”或“self-lessness”或“Self”[大写S],但不会突出“yourself”或“himself”等。 .

这是高亮功能:

function highlightWords($text, $words) {
    preg_match_all('~\w+~', $words, $m);
    if(!$m)
        return $text;
    $re = '~\\b(' . implode('|', $m[0]) . ')~i';
    $string = preg_replace($re, '<span class="highlight">$0</span>', $text);

    return $string;
}

【问题讨论】:

    标签: php search keyword highlight


    【解决方案1】:

    看来您的正则表达式开头可能有一个\b,这意味着一个单词边界。由于 'yourself' 中的 'self' 不是从单词边界开始的,所以它不匹配。摆脱\b

    【讨论】:

    • 你的意思是应该是$re = '~\(' . implode('|', $m[0]) . ')~i';
    【解决方案2】:

    试试这样的:

    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';
        return preg_replace($regex, '<span class="highlight">\\1</span>', $text);
    }
    
    $text = "isa this is test text";
    $words = array('is');
    
    echo highlight($text, $words);  // <span class="highlight">isa</span> <span class="highlight">this</span> <span class="highlight">is</span> test text
    

    循环是为了让每个搜索词都被正确引用...

    编辑:修改函数以在 $words 参数中采用字符串或数组。

    【讨论】:

      猜你喜欢
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 2019-03-21
      相关资源
      最近更新 更多