2015-04-18 44 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