在看到幾個線程垃圾查找術語匹配在HTML文檔中的正則表達式方法後,我用了簡單的HTML DOM PHP解析器(http://simplehtmldom.sourceforge.net/ )來獲取我以後的文本位,但是我想知道我的代碼是否是最優的。這感覺就像我循環了太多次。有沒有一種方法來優化以下循環?有沒有一種方法來優化查找頁面上的文本項目(而不是正則表達式)
//Get the HTML and look at the text nodes
$html = str_get_html($buffer);
//First we match the <body> tag as we don't want to change the <head> items
foreach($html->find('body') as $body) {
//Then we get the text nodes, rather than any HTML
foreach($body->find('text') as $text) {
//Then we match each term
foreach ($terms as $term) {
//Match to the terms within the text nodes
$text->outertext = str_replace($term, '<span class="highlight">'.$term.'</span>', $text->outertext);
}
}
}
例如,如果我在啓動循環之前確定是否有任何匹配,可能會有所不同嗎?
不確定。它遵循jquery(CSS)匹配方法。這有幫助嗎? – Jeepstone 2010-05-06 13:45:32