Remove specific HTML tags using PHP

There are times when you want to remove a specific HTML tag from an HTML block of text.

This could be an anchor(<a/>>) or an image(<img/>) perhaps.

You can use preg_replace to do this quite quickly and efficiently.

Remove an anchor:

$content = "Sample text <a href="#">Our anchor</a>. Etc etc"; $content = preg_replace('/&lt;\/?a[^&gt;]*&gt;/','',$content); //$content is now -&gt; "Sample text. Etc etc";
Code language: PHP (php)

Remove an image:

$content = "Sample text <img src="our_image.jpg">. Etc etc"; $content = preg_replace('/&lt;\/?a[^&gt;]*&gt;/','',$content); //$content is now -&gt; "Sample text. Etc etc";
Code language: PHP (php)
Tags:
Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Christopher Allen-Poole
Christopher Allen-Poole
7 years ago

OR, you can use strip_tags, which is the function that was actually *designed* for that purpose. Using regex for XML/HTML parsing is ill conceived.