我想从字符串中删除所有空的<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>';
?>
什么应该是您的最终/期望输出?你能否在你的问题中添加更多信息? –