m!<a(\s+[\w]+\s*\=\s*('[^']*'|"[^"]*"))*\s*>.*?</a\s*>!i
Update: at Abigail-II's suggestion, here's a modified version of the above, which accepts tags like <a href= foo_link>link text</a>. Of course, comments and criticism are always welcome.
m!<a(\s+[\w]+\s*\=\s*('[^']*'|"[^"]*"|[a-z0-9\-\._:]+))*\s*>.*?</a\s*>
+!i
This should be what you're looking for, because (if I got it right) it successfully detects any valid anchor tag. Once you've got that, you can substitute stuff for SGML entities wherever you haven't found a valid tag, like s/"/"/g and so forth. That way, any invalid code gets printed verbatim. Instead of:
A link with no closing tag where there really should be one...
You'll see
A <a href="#">link with no closing tag where there really should be one...
One limitation might pop up if the users start nesting anchors inside one another... This is why my initial response if it were my own app and server would be "get smarter users" :o)
Anyway, as always, there's bound to be faults with what I wrote above. Here's what I used to test it:
#!/usr/bin/perl
for (<>) {
m!<a(\s+[\w]+\s*\=\s*('[^']*'|"[^"]*"))*\s*>.*?</a\s*>!i ? pri
+nt "match: " : print "no match: ";
print;
}
And my dataset:
<a href="foo">blah</a>
<a href="foo>blah</a>
<a href='foo" >blah</a>
<a href="foo">blah</b>
<a href="foo's">bar</a>
<a name="blah" href="foo" >bar</a>
And my results:
match: <a href="foo">blah</a>
no match: <a href="foo>blah</a>
no match: <a href='foo" >blah</a>
no match: <a href="foo">blah</b>
match: <a href="foo's">bar</a>
match: <a name="blah" href="foo" >bar</a>
LAI
:eof |