Stripping HTML tags in Java

Viewed 63261

Is there an existing Java library which provides a method to strip all HTML tags from a String? I'm looking for something equivalent to the strip_tags function in PHP.

I know that I can use a regex as described in this Stackoverflow question, however I was curious if there may already be a stripTags() method floating around somewhere in the Apache Commons library that can be used.

13 Answers

Whatever you do, make sure you normalize the data before you start trying to strip tags. I recently attended a web app security workshop that covered XSS filter evasion. One would normally think that searching for < or &lt; or its hex equivalent would be sufficient. I was blown away after seeing a slide with 70 ways that < can be encoded to beat filters.

Update:

Below is the presentation I was referring to, see slide 26 for the 70 ways to encode <.

Filter Evasion: Houdini on the Wire

There may be some, but the most robust thing is to use an actual HTML parser. There's one here, and if it's reasonably well formed, you can also use SAX or another XML parser.

After having this question open for almost a week, I can say with some certainty that there is no method available in the Java API or Apache libaries which strips HTML tags from a String. You would either have to use an HTML parser as described in the previous answers, or write a simple regular expression to strip out the tags.

I've used nekoHtml to do that. It can strip all tags but it can just as easily keep or strip a subset of tags.

Related