在看到几个线程破坏了在 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);
}
}
}
例如,在开始循环之前确定是否有任何匹配项是否会有所不同?