tags:

views:

29

answers:

2

I'm wondering how I would approach the following problem with regular expressions. We run into the occasional problem of quote marks (") inside Alt tags which can cause rendering issues. Would it be possible to write a regular expression to find Img tags, but only when the ALT contains quotes?

For example these would be found

<img src="theImage.gif" width="81" height="24" border="0" style="display:block;" alt="Check "it" out">
<img src="theImage.gif" width="81" height="24" alt="Check "it" out"  style="display:block;">

But not these

<img src="theImage.gif" width="81" height="24" border="0" style="display:block;" alt="Check 'it' out">
<img src="theImage.gif" width="81" height="24" border="0" style="display:block;" alt="">
<img src="theImage.gif" width="81" height="24" border="0" style="display:block;">

Thanks in advance!

A: 

The problem is likely that the attribute value needs to be HTML encoded when rendered.

Doug D
Ok but he really wants to go the other way. He wants to HTML encode it post rendering. He wants to know if it can be done. It can't.
drachenstern
@drachenstern: agreed! The browser can't properly parse the invalid markup. The quotes must be encoded as " prior to rendering.
Doug D
@Doug D ~ Or alternately, you could escape them as \" but I would recommend the HTML encoding that you suggest too. Just pointing out an alternative.
drachenstern
+2  A: 

This problem is intractable because you might end up with something like:

<img src="theImage.gif" width="81" height="24" alt="foo" border="bar"> 

Would you interpret that as an alt value of foo and a border of bar, or as an alt value of foo" border="bar?

This is why you must properly escape your data before rendering it into HTML. You can't unstir a cup of tea.

Greg Hewgill
+1 for accuracy. +1 desired in addition for "can't unstir a cup of tea" ... I really must remember to use that more often. Ahhh entropy, you vile wench.
drachenstern
I understood the problem and didn't think it was possible, but figured I would ask.
dscl
@dscl ~ If you like his answer, check it off as the answer on the left.
drachenstern