0

我不确定如何更好地表达标题,但我的问题是突出显示功能不会突出显示单词末尾的搜索关键字。例如,如果搜索关键字是“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;
}
4

2 回答 2

2

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

于 2010-05-28T19:41:32.087 回答
0

尝试这样的事情:

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参数中采用字符串或数组。

于 2010-05-28T19:49:40.143 回答