PHP remove HTML tags from string using strip_tags

PHP remove HTML tags from string using strip_tags

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.

Related Posts

  1. MySQL value BETWEEN Two Columns in Laravel
  2. PHP tree structure for categories and sub categories without looping a MySQL query
  3. Email unique validation in Laravel ignore id on update
  4. WordPress Button Shortcode – Add button to WordPress editor
  5. WordPress shortcode – How to create shortcode in WordPress
  6. WordPress change URL in database using MySQL Query
  7. Enable shortcodes in widget WordPress
  8. PHP remove non-empty directory programmatically
  9. PHP File upload step by step with example
  10. Laravel 6 integrate AdminLte admin theme jeroennoten

2 Comments

  1. hello
    thanks for sharing ,i'm new php learner ,so I didn't get The "#" in second method ,could you please describe it ?

    1. Hi Shirin,
      Thanks for the comment.

      # is used for finding the specific character from the string.

      # means matches the characters #< literally (case sensitive). #< find the < character from the string.

      + Quantifier — Matches between one and unlimited times, as many times as possible

Leave a Reply

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

Search Posts

Subscribe To Newsletter

Get Early Access To New Articles, Plugins, Discount Codes And Quickly Brief Updates about tips and tricks

Join 357 other subscribers

%d bloggers like this: