views:

1125

answers:

6

I need a RegEx pattern for extracting all the properties of an image tag.

As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.

I was looking at this solution http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php but it didn't quite get it all:

I come up something like:

(alt|title|src|height|width)\s*=\s*["'][\W\w]+?["']

Is there any possibilities I'll be missing or a more efficient simple pattern?

EDIT:
Sorry, I will be more specific, I'm doing this using .NET so it's on the server side.
I've already a list of img tags, now I just need to parse the properties.

+6  A: 

As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.

It won't. Use a HTML parser if you have to parse "evil" (from an unknown source) HTML.

Tomalak
A: 

If you want all attribute values, might I suggest using the DOM? Something like element.attributes will work well.

If you insist on a regex //\b\w+="[^"]+"// should get everything.

sblundy
+1  A: 

If performance is not a big concern I'd go with an html parser (like BeautifulSoup in python) if you are doing this server-side or jquery or just plain javascript if you are doing it client-side. Granted it is overkill but it is a lot quicker, less likely to have bugs (since they've thought of the corner cases), and it will handle the potential malformedness.

rz
A: 

Your best bet is to use something like HTML Agility Pack instead of using regex. It's designed to handle a lot of cases and can save you more than a few headaches due to hammering out edge cases

James Hollingshead
A: 

Before comitting yourself to regex, see what it can do: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454

ProfK
A: 
/<img(\s+([a-z]{3,})=(["']([^"']*)["']|[\S]))+\s*/?>/i

A match_all on this, will return (format depends on your library, but key indexes are):

0 -> image tag
1 -> attribute
2 -> attribute name
3 -> attribute value (with enclosing quotes if exists)
4 -> attribute value (without enclosing quotes if it has them, otherwise empty, use 3)
Tor Valamo