2013-07-02 33 views
0

我正在使用以下函數突出顯示從字符串搜索的關鍵字。它工作正常,但沒有什麼問題。只強調從字符串中鍵入的關鍵字在php

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

什麼是你用'\\ B','原因\\ w'和'\\ W'而不是'\ b','\ w'和'\ W'? – h2ooooooo

+0

這兩種情況下都會得到相同的結果。請指教。 – KRA

+0

@KRA,你想要什麼輸出準確的樣本輸入? – Dogbert

回答

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> 
+0

這簡直棒極了!非常感謝,它的工作非常完美... – KRA

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

我希望這將有助於充分。