simple_html_dom是php解析html的简便而强大的工具。simple_html_dom.php源码文件可以在网上搜到,然后include进来就可以调用了。
但是simple_html_dom中没有提供删除指定标签的功能,所以下面实现以下,只要在simple_html_dom_node类中加上如下代码:
/*add by wangyu 2013-08-19
*description:remove node with given tag
*index begin with 0
*/
function find_and_remove(&$p, $tag, &$index)
{
static $is_find = 0;
if($is_find == 1)
{
return;
}
$idx = 0;
foreach($p->nodes as $n)
{
if($n->tag===$tag && $index===0)
{
unset($p->nodes[$idx]); //remove the start tag, such as <img src="">
if(preg_match("<[\s ]*/[\s ]*img[\s ]*>", $p->nodes[$idx+1]->outertext))
{
unset($p->nodes[$idx+1]); //remove the end tag, such as </img>
}
$is_find = 1;
return;
}
if($n->tag === $tag)
{
$index--;
}
if($n->has_child())
{
$this->find_and_remove($n, $tag, $index);
}
$idx++;
}
}
function remove_node($tag, $index)
{
if($index < -1 || $tag === null || $tag === "")
{
return;
}
if($this->tag !== 'root')
{
return;
}
$this->find_and_remove($this, $tag, $index);
}
然后在simple_html_dom类中加入如下代码
function remove_node($tag, $index)
{
$this->root->remove_node($tag, $index);
}