PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to remove empty html tags (which contain whitespaces and/or their html codes)

 November 20, 2022     html, php, preg-replace, regex     No comments   

Issue

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>

Solution

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.



Answered By - karthik manchala
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing