2012-01-24 52 views
0

可能重複:
Highlight keywords in a paragraph正則表達式突出顯示搜索字詞

我一直在HTML或純文本字符串突出的搜索字詞的想法中掙扎。我看到很多例子,只是不起作用,所以這裏是我的破解。請給我一些情況下,這將打破HTML或不會工作。我能想到的唯一兩種情況是:如果在文本字符串中有「>我不是計算機」和格式不正確的html。所以這是代碼。謝謝你,我希望它可以幫助別人

function search_highlight($text,$search_terms) 
{ 
    $color = array('#FFFF00','#00FFFF','#FF9900','#00FF00','#CCCCCC','red','grean','orange'); 
    $count = 0; 

    if (! is_array($search_terms)) 
    { 
    $search_terms = explode(' ', $search_terms); 
    } 

    // Highlight each of the terms 
    foreach ($search_terms as $term) 
    { 
    //skip blank terms that arise from double spaces 
    if(! $term) continue; 

    //Regex Explained: 
    //The regex first matches a word boundary 
    //Next it matches the search term liternal 
    //Next it matches a word boundary 
    //Next is matches, but doesn't include the following regex... 
    //Anything other than the literals <and> zero or more times 
    //Next it will match either a < literal or the end of the string 
    $text = preg_replace('/\b('.preg_quote(trim($term)).')\b(?=[^><]*<|.$)/i', '<span style="background-color:'.$color[$count].'">\1</span>', $text); 

    //increment counter for new color 
    $count++; 
} 
return $text; 
} 
+1

他們所有人可能不工作的原因是因爲你想用DOM做而不用正則表達式 – Gordon

+0

你用JavaScript來遍歷DOM嗎?如果有,你會建議任何插件?我只看到一個php DOM解析器,它很慢。 – John

+0

無論是JavaScript或http://php.net/dom – Gordon

回答

2

我會用DOMDocument類這一點,簡單地做對節點內容的純文本替換,而不是試圖想出一個忍者正則表達式。

+0

很好基於戈登的評論和你的評論我將去與DOM方法,但使用JavaScript,所以我可以節省一些交貨時間。感謝您的見解。 – John