Remove HTML tags from a string in PHP

In this short article, we will explain to you how to remove HTML tags from a string in PHP. Sometimes we need to get only the content part without HTML tags so today we will show you a simple way to remove HTML tags.

Here we will use two different PHP methods such as predefined method and user defined method to remove the HTML tags.

Ways to remove HTML tags from a string in PHP

  1. Using built-in function
  2. Using custom function

1. Using built-in function

We have built-in php function strip_tags() to remove HTML tags from a string.

Syntax

Here, $str parameter is required and $allowable_tags parameter is optional. Therefore the $allowable_tags are not removed from the string. You can also pass multiple tags together as a string.

Example 1:

Let’s take a simple example where we will pass only required parameters into the strip_tags() function.

Example 2:

In the second example, if we want to ignore the <a> tag from the string and remove the rest of all the HTML tags then pass the <a> tag in the second argument of the strip_tags() php function.

Example 3:

If you want to ignore the multiple HTML tags during the removal from the string then pass the all tags (i.e. <a><br>) in a single argument as a string.

Check out the below code where we have passed the <a><br> tags in the second argument of the strip_tags() function.

2. Using custom function

Here we have created a custom function to remove HTML tags which you want. This function will work a little differently than the built-in php function. It will remove all the HTML tags which we will pass as arguments.

Check out the following code for more understanding.

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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