如何删除空白的html标签(包含空格和/或其html代码) [英] How to remove empty html tags (wich containing whitespaces and/or their html codes)

查看:102
本文介绍了如何删除空白的html标签(包含空格和/或其html代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要preg_replace的正则表达式。



这个问题在另一个问题中没有回答,因为并非所有要移除的标记都不是空的。



我不仅要从HTML结构中删除空标签,而且还要包含换行符以及空格和/或其html代码。



可能的代码有:

< br />> &安培; NBSP; &安培; thinsp; &安培; ensp; &安培; EMSP; &安培;#8201; &安培;#8194; &#8195;



在移除匹配标记之前:

 << ; DIV> 
< h1>这是一个html结构。< / h1>
< p>这不是空的。< / p>
< p>< / p>
< p>< br />< / p>
< p> < br /> &安培;; thinsp;< / p为H.
< p>& nbsp;< / p>
< p> &安培; NBSP; < / p为H.
< / div>

删除匹配标签后:

 < DIV> 
< h1>这是一个html结构。< / h1>
< p>这不是空的。< / p>
< / div>


解决方案

您可以使用以下内容:

 <([^> \s] +)[^>]>(?: \ s *(?: < br \ /> |& nbsp; |& thinsp; |& ensp; |& emsp; |&#8201; |&#8194; |&#8195;)\s *)*< \ / \1> 

然后换成''(空字符串)



请参阅 DEMO



注意:这也适用于带有属性的空html标签。


Need a regex for preg_replace.

This question wasn't answered in "another question" because not all tags I want to remove aren't empty.

I have not only to remove empty tags from an HTML structure, but also tags containing line breaks as well as white spaces and/or their html code.

Possible Codes are:

<br /> &nbsp; &thinsp; &ensp; &emsp; &#8201; &#8194; &#8195;

BEFORE removing matching tags:

<div> 
  <h1>This is a html structure.</h1> 
  <p>This is not empty.</p> 
  <p></p> 
  <p><br /></p>
  <p> <br /> &;thinsp;</p>
  <p>&nbsp;</p> 
  <p> &nbsp; </p> 
</div>

AFTER removing matching tags:

<div> 
  <h1>This is a html structure.</h1> 
  <p>This is not empty.</p> 
</div>

解决方案

You can use the following:

<([^>\s]+)[^>]*>(?:\s*(?:<br \/>|&nbsp;|&thinsp;|&ensp;|&emsp;|&#8201;|&#8194;|&#8195;)\s*)*<\/\1>

And replace with '' (empty string)

See DEMO

Note: This will also work for empty html tags with attributes.

这篇关于如何删除空白的html标签(包含空格和/或其html代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆