We help IT Professionals succeed at work.
Get Started

RegEx to match style="something" ??

CAS-IT asked
Last Modified: 2012-05-12
Hi guys,

I'm trying to make a regex that removes in-line styles from HTML. I.e. <div style="color: red"> becomes <div>.

I also want to make sure that this matches any kind of messed-up HTML it receives, like whitespace in the middle of the thing, single quotes or double quotes, uppercase STYLE or lowercase, or something like sTyLe or whatnot. It needs to be fool-proof.

Here's what I've got:


The i takes care of the case, so we can start with /style/i

Then, I need to make sure we match whitespace between style and the = sign. So I add \s*.

Then I match the = sign.

Then I match more whitespace with \s*

Then I need to match the first quote, so I've used ('|") to match single or double quotes.

Then, we match anything, for which I use .*

Then we match the closing quote with another ('|").

Ok. So the problem here is the "anything" part. When this runs, it not only matches

style="color: red"

But it also matches

style="color: red">Hey guys! what'

So, it can grab HTML that it's not supposed to.

But, I can't just say stop at the first quote, because you can have valid in-lie styles that contain quotes. Like:

style="background: url('mygraphic.jpg') top left no-repeat);"

So, this one has a ' in it. So it would match.

I'm stuck!!

Watch Question
Top Expert 2010
This problem has been solved!
Unlock 3 Answers and 7 Comments.
See Answers
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE