0

我有一个像这样的文件:

<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 的类名“remove”替换 div。我试过这个:

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

那没起效。这个替换的正确正则表达式应该是什么?

4

2 回答 2

0

正如评论中所述,您不应该使用正则表达式来解析 HTML。因为<div>如果里面有其他嵌套<div>的 ' ,你就没有理智的方法来提取它。IE

<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.
于 2013-07-11T07:25:03.313 回答
0

试试这个代码。

preg_replace("/<div class='remove'>(.*?)<\/div >/i", "<div class="newClass">Newthings</div> ", $Cont);
于 2013-07-11T07:13:38.513 回答