2010-05-06 30 views
0

在看到幾個線程垃圾查找術語匹配在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); 
    }  
    } 
    } 

例如,如果我在啓動循環之前確定是否有任何匹配,可能會有所不同嗎?

回答

0

你不需要外部的foreach循環;在格式良好的文檔中通常只有一個主體標籤。相反,只需使用$body = $html->find('body',0);即可。

但是,由於只有一次迭代的循環在運行時本質上等同於根本不循環,因此可能不會對性能造成太大影響。因此,實際上,即使在原始代碼中,您實際上只有2個嵌套循環,而不是3.

0

說到無知,find是否會採用任意XPath表達式?如果是這樣,您可以將兩個外環折成一個:

foreach($html->find('body/text') as $body) { 
    ... 
} 
+0

不確定。它遵循jquery(CSS)匹配方法。這有幫助嗎? – Jeepstone 2010-05-06 13:45:32

相關問題