Tutorial :How to remove all html tags except img?


I got some html text, which contains all kinds of html tags, such as <table>, <a>, <img>, and so on.

Now I want to use a regular expression to remove all the html tags, except <img ...> and </img>(and upper case <IMG></IMG>).

How to do this?


My task is very simple, it just print the text content(including images) of a html as a summary in the front page, so I think regular expression is good and simple enough.


Maybe a sample will make my question better to understand :)

There are some html text:

<html>    <head></head>    <body>       Hello, everyone. Here is my photo: <img src="xxx.jpg" />.        And, <a href="xxx">know more</a> about me!    </body>  </html>  

I want to keep , and remove other tags. Following is what I want:

Hello, everyone. Here is my photo: <img src="xxx.jpg" />. And, know more about me!  

Now I code like this:

html.replaceAll("<.*?>", "")  

But it will remove all the content between < and >, but I want to keep <img xxx> and </img>, and remove the other content between < and >

Thank for everyone!


I tried a lot, this regular expression seems work for me:


My code is:

html.replaceAll('(?i)<(?!img|/img).*?>', '');  


Do not use a RegEx to parse HTML. See here for a compelling demonstration of why.

Use an HTML parser for your language/platform.

  • Here is a java one (HTML parser)
  • For .NET, the HTML Agility Pack is recommended
  • For ruby, there is nokogiry, though I am not a ruby dev, so don't know how good it is


A simple answer to why Do not use a RegEx is:

Regexp can't parse recursive grammar such as:

S -> (S)  S -> Empty  

Because this kind of grammar has infinite state.

Since HTML has a recursive grammar you can simply use regexp.

SPAN -> <span>SPAN</span>  SPAN -> text  

But in your case you can express a regular expression that is not recursive.



Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »