2015-04-18 50 views
2

我想從字符串中刪除所有空的<a>標籤。刪除沒有孩子的元素DOM PHP

這樣:

<a href="http://www.google.com"></a> 

而不是:

<a href="http://www.google.com">Not empty</a> 

然而:

<a href="http://www.google.com"><img src="puppy.jpg" alt="Not empty"></a> 

被移除。

編輯: 基本上圖像正在被刪除,因爲它們似乎有一個空的nodeValue。我想保留圖像。爲什麼在<a>標籤之間存在圖像時nodeValue返回空白?

這裏是我的嘗試:

<?php 
$content_before=' 
so: 
<a href="http://www.google.com"></a> 

and not: 
<a href="http://www.google.com">Not empty</a> 

However: 
<a href="http://www.google.com"><img src="puppy.jpg" alt="Not empty"></a> 
'; 
$dom=new domDocument; 
@$dom->loadHTML($content_before); 
$dom->preserveWhiteSpace = true; 

$anchors=$dom->getElementsByTagName('a'); 
foreach($anchors as $a) 
{ 
    $as[] = $a; 
} 
foreach($as as $a) 
{ 
    $nodevalue=$a->nodeValue; 
    $nodevalue=trim($nodevalue); 

    if(empty($nodevalue)&&is_object($a)) 
    { 
     #remove links without nodevalues 
     $a->parentNode->removeChild($a); 
    } 
} 
$content=$dom->saveHTML(); 
echo 'before:<br><textarea>'.$content_before.'</textarea>'; 
echo 'after<br><textarea>'.$content.'</textarea>'; 

#what $content becomes: 
$content=' 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body><p>so: 


and not: 
<a href="http://www.google.com">Not empty</a> 

However: 
</p></body></html>'; 

#What I want it to be: 
$content_after=' 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> 
<html><body><p>so: 

and not: 
<a href="http://www.google.com">Not empty</a> 

However: 
<a href="http://www.google.com"><img src="puppy.jpg" alt="Not empty"></a> 
</p></body></html>'; 
?> 
+0

什麼應該是您的最終/期望輸出?你能否在你的問題中添加更多信息? –

回答

1

另一種方法是使用xpath查詢,然後得到它沒有/空孩子的所有元素。在此之後,刪除所有這些元素與迴歸:

$dom = new DomDocument; 
@$dom->loadHTML($content_before); 
$dom->preserveWhiteSpace = true; 
$xpath = new DOMXpath($dom); 

$empty_anchors = $xpath->evaluate('//a[not(*) and not(text()[normalize-space()])]'); 
$i = $empty_anchors->length - 1; 
while ($i > -1) { 
    $element = $empty_anchors->item($i); 
    $element->parentNode->removeChild($element); 
    $i--; 
} 

echo $dom->saveHTML(); 
1

您可以檢查是否firstChild存在,只是改變你的foreach環路:

foreach($as as $a) 
{ 
    if($a->firstChild === NULL && is_object($a)) 
    { 
     #remove links without nodevalues 
     $a->parentNode->removeChild($a); 
    } 
} 

則firstChild

這樣做的第一個孩子節點。如果沒有這樣的節點,則返回NULL