Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A regular expression to remove a given (x)HTML tag from a string

Tags:

html

string

regex

Let's say I have a string holding a mess of text and (x)HTML tags. I want to remove all instances of a given tag (and any attributes of that tag), leaving all other tags and text along. What's the best Regex to get this done?

Edited to add: Oh, I appreciate that using a Regex for this particular issue is not the best solution. However, for the sake of discussion can we assume that that particular technical decision was made a few levels over my pay grade? ;)

like image 281
Electrons_Ahoy Avatar asked Sep 22 '08 17:09

Electrons_Ahoy


1 Answers

Attempting to parse HTML with regular expressions is generally an extremely bad idea. Use a parser instead, there should be one available for your chosen language.

You might be able to get away with something like this:

</?tag[^>]*?>

But it depends on exactly what you're doing. For example, that won't remove the tag's content, and it may leave your HTML in an invalid state, depending on which tag you're trying to remove. It also copes badly with invalid HTML (and there's a lot of that about).

Use a parser instead :)

like image 172
Dan Avatar answered Oct 20 '22 22:10

Dan