有没有一种方法来优化查找页面上的文本项目(而不是正则表达式)

问题描述:

在看到几个线程垃圾查找术语匹配在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); 
    }  
    } 
    } 

例如,如果我在启动循环之前确定是否有任何匹配,可能会有所不同吗?

你不需要外部的foreach循环;在格式良好的文档中通常只有一个主体标签。相反,只需使用$body = $html->find('body',0);即可。

但是,由于只有一次迭代的循环在运行时本质上等同于根本不循环,因此可能不会对性能造成太大影响。因此,实际上,即使在原始代码中,您实际上只有2个嵌套循环,而不是3.

说到无知,find是否会采用任意XPath表达式?如果是这样,您可以将两个外环折成一个:

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

不确定。它遵循jquery(CSS)匹配方法。这有帮助吗? – Jeepstone 2010-05-06 13:45:32