正则表达式删除div

时间:2013-07-11 07:04:37

标签: php regex

我有一个类似的文件:

<div clas='dsfdsf'> this is first div </div>
<div clas='dsfdsf'> this is second div </div>
<div class="remove"> 
  <table> 
  <thead> 
   <tr> 
     <th colspan="2">Mehr zum Thema</th> 
  </tr> 
</thead> 
<tbody>
  <tr> this is tr</tr>
  <tr> this row no 2 </tr>
</tbody>
</table>
</div>
 <div clas='sasas'> this is last div </div>

我在这样的变量中得到了这个文件内容:

$Cont = file_get_contents('myfile');

现在我想用preg_replace用class name'remove'替换div。我试过这个:

$patterns = "%<div class='remove'>(.+?)</div>%";  
$strPageSource = preg_replace($patterns, '', $Cont);

它不起作用。这个替换的正确表达式应该是什么?

2 个答案:

答案 0 :(得分:0)

试试这段代码。

preg_replace("/<div class='remove'>(.*?)<\/div >/i", "<div class="newClass">Newthings</div> ", $Cont);

答案 1 :(得分:0)

正如评论中所述,您不应该使用正则表达式来解析HTML。因为如果内部存在其他嵌套<div>,则没有合理的方法来提取<div>。即。

<div clas='dsfdsf'> this is second div </div>
<div class="remove"> 
      some text <div>nested div</div> more text and some elements<br />
</div>

您要做的是找到<div class="remove">的位置,然后按以下方式浏览HTML(解析它)

1) set $nesting_counter = 0
2) proceed through HTML until you encounter either <div> or </div>
    a) if found <div>
           $nesting_counter++ and go to point 2)
    b) if found </div>
           if $nesting_counter > 0
               $nesting_counter-- and go to point 2)
           else
               you've found the closing tag for your `<div class="remove">`. remember current position and just remove that substring.