To remove all HTML tags from a string in php, the easiest way is to use the strip_tags() function.

I'm a string with HTML!

"; echo strip_tags($string_with_html_tags); //Output: I'm a string with HTML!

When working with strings in php, the ability to easily manipulate them and remove certain characters is very useful.

Many times when we are using with user input from a form or trying to scrape some data, we run into strings with HTML tags.

Luckily, the php strip_tags() function exists and allows us to remove all HTML tags from a string. strip_tags() tries to return a string with all NULL bytes, HTML and php tags remove from a given string.

We can get rid of the HTML tags in a string by simply passing a string to strip_tags().

Below is a simple example of getting stripping the HTML tags from a string in php with strip_tags().

I'm a string with HTML!

"; echo strip_tags($string_with_html_tags); //Output: I'm a string with HTML!

Keeping Certain HTML Tags and Stripping All Other Tags with strip_tags() in php

There is a second optional parameter for the strip_tags() function which allows us to keep certain HTML tags when using strip_tags().

The ‘allowed_tags’ parameters gives us the option to specify tags which should not be removed.

For example, if we want to keep paragraph tags, we would pass “

” for ‘allowed_tags’;

Below is a simple example of how to use strip_tags to remove all HTML tags except “

” tags.

I'm a string with HTML!

"; echo strip_tags($string_with_html_tags, "

"); //Output:

I'm a string with HTML!

Hopefully this article has been useful for you to learn how to use the strip_tags() function to remove HTML tags from a string in php.

Categorized in:

PHP,

Last Update: February 26, 2024