PHP remove HTML tags from string using strip_tags

0

Today, We are going to learn PHP remove HTML tags from a string. PHP provides the strip_tags function for removing HTML tags from a string. We can also remove the HTML tag from a string using preg_replace function. Both methods remove HTML tags but the output is different. Today, We are going to learn both methods step by step with output.

PHP remove HTML tags from a string

We are going to learn the first example using strip_tags function.

Remove HTML tags using strip_tags function

$string = strip_tags("Hello <b>world!</b>");

The strip_tags function removed HTML tags from the string. The output is Hello world! Now Let’s see another example. If we removed the space after Hello words like below.

$string = strip_tags("Hello<b>world!</b>");

The output of the above code is “Helloworld!” Now, What if I want to add space after Hello words after removing the HTML tags. We can achieve that output using preg_replace function.

So, let’s see the second example for removing HTML tags from a string and get the output like “Hello world!” instead of “Helloworld!”.

Remove HTML tags using preg_replace function

$string = preg_replace('#<[^>]+>#', ' ', 'Hello<b>world!</b>');

The preg_replace function returns the output like “Hello world!” instead of “Helloworld!”.

We check both method with the example Now, choose the which method is helpful for you and use it for removing HTML tags from a string.

If you face any kind issue after using above code please write the comment below.

Share.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.