2012-01-24 17 views
0

可能性の重複:私は、HTMLや純粋なテキスト文字列で検索用語を強調するという考えで苦労されている
Highlight keywords in a paragraph正規表現のハイライト検索用語

。私は多くの例を見てきましたが、ここではうまくいきませんでした。これがhtmlを壊したり、うまくいかないケースを教えてください。私が思いつくことができる唯一の2つのケースは次のようなものです:テキスト文字列の中に "私はコンピュータよりも"と書かれた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

なぜ彼らはおそらく仕事をしないのですか?あなたはRegexではなくDOMでそれをしたいからです。 – Gordon

+0

DOMをトラバースするためにjavascriptを使用していますか?もしそうなら、あなたが提案するプラグインがありますか?私は1つのPHP DOMパーサーしか見ていないし、それはかなり遅いです。 – John

+0

javascriptまたはhttp://php.net/dom – Gordon

答えて

2

私はこのためにDOMDocumentクラスを使用して、単純にプレーンテキストではなく、忍者の正規表現を思い付くしようとするノードの内容に置き換えるんに役立ちます願っています。

+0

Gordonのコメントとあなたのコメントに基づいていますが、私はDOMのアプローチに行くつもりですが、javascriptを使用して配送時間を節約できます。あなたの洞察に感謝します。 – John