0

見出しが始まる前にすべての画像タグを削除したいのですが、同じようにネストされていません。次に、空のタグを削除します。

<div class="c2">
  <img src="image/file" width="480" height="360" alt="Image" />
</div>
<div class="c2">
  <div class="headline">
    headline
  </div>
  <div class="headline">
    headline2
  </div>
</div>

のようなさまざまなネストされたタグ

<div class="c2">
  <p>
    <img src="image/A.JPG" width="480" height="319" alt="Image" />
  </p>
  <div class="headline">
    A headline
  </div>
</div>

再帰的に解決できると思いますが、方法がわかりません。

ご協力いただきありがとうございます!

4

1 に答える 1

0

EDIT :またはの<img>後にのみ削除する場合は、次の xpath を使用します。<div><div class="headline>"<div class="headline">

$imgs = $xpath->query("//img[../following-sibling::div[1]/div/@class='headline' or ../following-sibling::div[1]/@class='headline']");

動作を確認してください: http://codepad.viper-7.com/QhprLP

次のようにします。

$doc = new DOMDocument();
$doc->loadHTML($x); // assuming HTML in $x
$xpath = new DOMXpath($doc);
$imgs = $xpath->query("//img"); // select all <img> nodes

foreach ($imgs as $img) { // loop through list of all <img> nodes
$parent = $img->parentNode; 
$parent->removeChild($img); // delete <img> node
if ($parent->childNodes->length >= 1) // if parent node of <img> is empty delete it
        $parent->parentNode->removeChild($parent);
}

echo htmlentities($doc->saveHTML()); // display the new HTML

動作を確認してください: http://codepad.viper-7.com/350Hw6

于 2013-05-09T20:42:02.380 に答える