How to Remove HTML Tags from Text and WYSIWYG in PHP

One of my favorite projects to write for clients are Custom CMS to allow them to control the content displayed on their pages. When doing this, I always take into consideration that the client has little to no knowledge of programming, and probably is without a clue as to what HTML is. For this reason, learning how to remove html tags from text in PHP using strip_tags is an essential tool for any programmer, especially when you are attempting to keep the formatting of the pages marked up properly and without unnecessary HTML characters.

When writing my backends, TinyMCE’s WYSIWYG editor is my one and only choice, as it is well documented, supported, and sets the precident for other WYSIWYG editors. What is so fantastic about using these for a custom CMS is not only because it allows the individual to format their pages to their liking, but more importantly, because the data handling on the backend is incredibly easy and can be stripped and formatted in just a few lines of text.

Here is a quick example:

<h1>This is H1 text</h1>

This text would be formatted like so:

This is H1 Text

When using the strip_tags(); function, PHP will automatically take out all HTML formatting that the user may have inputted. All it takes is a few lines of code:

/** always use isset to ensure 
    the variable holds data
if(isset($_POST['user_input'])) { 

//$stripped_var = strip_tags($var);
 $user_input = strip_tags($_POST['user_input']);

Now $user_input will be stripped of all HTML characters, formatting it to look like so:

This is H1 Text

That’s it! Now any user inputted text will be stripped of all HTML characters, allowing for the pages and templates to not be improperly formatted.

Leave a Comment

Your email address will not be published. Required fields are marked *