2013-05-09 87 views
0

我想在標題開始前刪除所有圖像標記,但它們嵌套方式不同。然後刪除空標籤。php刪除指定標記前的標記

<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> 

嵌套的標籤我認爲這可能是遞歸解決,但我不知道怎麼辦。

感謝您的幫助!

+2

你想用PHP做到這一點?解析HTML文件並刪除元素? – Lix 2013-05-09 19:49:37

+0

是的,我嘗試了簡單的PHP,但沒有成功。 – user1768700 2013-05-09 19:56:11

+1

我討厭成爲那個人,但使用jQuery會更容易... – EmmyS 2013-05-09 20:16:56

回答

0

編輯:如果你只想刪除<img>其次<div><div class="headline>"<div class="headline">,使用此XPath:

$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

+0

感謝您的回答,但我想保留所有圖像後的healine。 – user1768700 2013-05-10 07:10:16

+0

@ user1768700:看我的編輯! – michi 2013-05-11 13:25:59