我想從字符串中刪除所有空的<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>';
?>
什麼應該是您的最終/期望輸出?你能否在你的問題中添加更多信息? –