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 で div をクラス名「remove」に置き換えたいと思います。私はこれを試しました:

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

それは動かなかった。この置換の正しい正規表現は何ですか?

4

2 に答える 2

0

このコードを試してください。

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

コメントに記載されているように、正規表現を使用して HTML を解析するべきではありません。内部に<div>他のネストされた 's がある場合、それを抽出する適切な方法がないためです。<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.
于 2013-07-11T07:25:03.313 に答える