在php中只突出显示字符串中键入的关键字

时间:2013-07-02 09:46:38

标签: php regex string

我正在使用以下功能来突出显示字符串中的搜索关键字。它工作正常,但几乎没有问题。

$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);
}

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

您不要使用php突出显示搜索词,需要一些时间才能找到并替换每个单词。

使用jquery它会比php更容易。

简单示例:

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');

我希望它会有所帮助。

相关问题