2013-02-15 37 views
0

我需要一些帮助。我研究过正则表达式,但还没有完全理解它的实现。如果父级包含给定的类或ID,我需要一个将删除所有标签及其子级的片段。PHP:删除所有包含给定类别或标识的标签

例子:

<?php 

function remove_tag($find="",$html) 
{ 
    # Remove multiple #IDs and classes at once 

    # When given a string (separating objects with a comma) 
    if (is_string($find)) 
    { 
     $objects = explode(',', str_replace(' ', '', $find); 
    } else if (is_array($find)) { 
     $objects = $find; 
    } 

    foreach ($objects as $object) 
    { 
     # If ID 
     if (substr($object,0,1) == '#') 
     { 
      # regex to remove an id 
      # Ex: '<ANYTAG [any number of attributes] id='/"[any number of ids] NEEDLE [any number of ids]'/" [any number of attributes]>[anything]</ENDTAG [anything]>' 

     } 

     if (substr($object,0,1) == '.') 
     { 
      # remove a class 
      # Ex: '<ANYTAG [any number of attributes] class='/"[any number of classes] NEEDLE [any number of classes]'/" [any number of attributes]>[anything]</ENDTAG [anything]>' 
     } 

     # somehow remove it from the $html variable? 
    } 
} 

很抱歉,如果这是一个新手的问​​题,感谢您的时间! :)

-Pat

+2

如果你用正则表达式解析HTML,他会来http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – 2013-02-15 23:59:33

+1

许多人向我证明,尽管我第一次不同意,但简单的正则表达式并不是HTML解析的可靠方式。总会有毛病。因此,如果此解析的代码是用户输入,请使用http://htmlpurifier.org/。 – 2013-02-15 23:59:57

+0

嗯...你想删除类或删除元素? 那么你想

成为
(通过删除类classNumberOne)? 或者你想要具有给定类的元素,只是为了隐藏?如果没有完全理解你想实现什么,那么我可能会在javaScript中完成它(如果我已经理解了你想要的)。沿着getElementById的行并放置样式显示:none;在上面。对不起,如果我误解了你的问题...我试过了。 :-) – Zeth 2013-02-16 00:01:55

回答

2

您可以使用,而不是正则表达式,XPath查找要删除文档中的所有元素。

DOMDocumentXPath对我来说似乎是一个好的开始。

您可以使用DOMNode::removeChild()方法删除子项,并使用DOMXPath类来评估XPath,以获取需要删除的节点。