0

我正在使用以下函数来突出显示字符串中搜索到的关键字。它工作正常,但问题不大。

$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);

使用以下功能,它突出显示“简单”和“文本”单词,我希望它应该只突出显示“sim”和“文本”单词。我需要进行哪些类型的更改才能达到此结果。请指教。

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="SuccessMessage">\\1</span>', $text);
}
4

2 回答 2

1

为此,您需要将所有相关文本分组。

完整代码:(我已经标记了我已更改的行。)

$text="This is simple test text";
$words="sim text";
echo highlight($text, $words);

function highlight($text, $words)
{
    if (!is_array($words))
    {
        $words = preg_split('#\\W+#', $words, -1, PREG_SPLIT_NO_EMPTY);
    }
    # Added capture for text before the match.
    $regex = '#\\b(\\w*)(';
    $sep = '';
    foreach ($words as $word)
    {
        $regex .= $sep . preg_quote($word, '#');
        $sep = '|';
    }
    # Added capture for text after the match.
    $regex .= ')(\\w*)\\b#i';
    # Using \1 \2 \3 at relevant places.
    return preg_replace($regex, '\\1<span class="SuccessMessage">\\2</span>\\3', $text);
}

输出:

This is <span class="SuccessMessage">sim</span>ple test <span class="SuccessMessage">text</span>
于 2013-07-02T10:23:33.170 回答
0

Hi dont use php to highlight search words its takes some times to find and replace each word.

Use jquery it will be easier then php.

Simple example:

function highlight(word, element) {
var rgxp = new RegExp(word, 'g');
var repl = '<span class="yourClass">' + word + '</span>';
element.innerHTML = element.innerHTML.replace(rgxp, repl); }

highlight('dolor');

I hope it will help full.

于 2013-07-02T10:22:02.967 回答