[英]Remove blank tags with simple HTML DOM parser
I have a html input which contains many blank strong tags. 我有一个HTML输入,其中包含许多空白的强标签。 so i want to remove these blank strong tags from html.I have used simple HTML DOM but it doesn't work 所以我想从html中删除这些空白的强标签。我使用了简单的HTML DOM,但是它不起作用
foreach($html->find('strong') as $strong)
{
if(trim($strong->innertext) == '')
{
echo 'blank strong';
}
}
In above code, i have checked the if condition without trim function, but still no success . 在上面的代码中,我检查了if条件是否没有修剪功能,但仍然没有成功。 How to remove blank tags or tags which contains only whitespace from html code ? 如何从HTML代码中删除空白标签或仅包含空格的标签?
You didn't give an example but lets say you have this markup, you could use outertext
. 您没有给出示例,但是可以说您具有此标记,可以使用outertext
。 (By the way, I can't also find a some kind of removeChild()
on the manual). (顺便说一句,我在手册上也找不到某种removeChild()
)。
$html_string = '
<div class="container">
<strong>Text1</strong>
<strong>Text2</strong>
<strong>Text3</strong>
<strong></strong>
<strong>Text5</strong>
</div>
';
$html = str_get_html($html_string);
foreach($html->find('strong') as $element) {
if(trim($element->innertext) == '') {
$element->outertext = '';
}
}
echo htmlentities($html);
Should output: 应该输出:
<div class="container"> <strong>Text1</strong> <strong>Text2</strong> <strong>Text3</strong> <strong>Text5</strong> </div>
The fourth <strong></strong>
tag should be gone now. 第四个<strong></strong>
标记现在应该消失了。
You can just use jquery to remove blank tags. 您可以只使用jquery删除空白标签。
$(document).ready(function(){
$('strong').each(function(){
if($.trim($(this).html()) == ''){
$(this).remove();
}
})
})
You can also use preg_replace to remove empty html tags. 您也可以使用preg_replace删除空的html标签。
$html = "abc<strong></strong><p>dd</p><b>non-empty</b><strong> ashish </strong><strong><a>click</a></strong><strong> </strong><strong>test</strong>";
$pattern = "/<[^\/>]*>([\s]?)*<\/[^>]*>/"; // pattern for removing all empty tags
echo preg_replace($pattern, '', $html);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.