http://www.perlmonks.org?node_id=188933


in reply to How do I write a regex for 'does not contain' a string.

You're relying on a couple of things here, which may be OK and which may not be. If they are, disregard the code, which was written on the fly (but works with the sample input!). First, consider a line such as:

<img src="blern.gif" /><span style="display:block" >foo!</span>

That's going to pass your test. There's also that pesky problem that the tag need not all be on the same line:

<img src="gern.jpg" border="0" style="display:block" />

Pile on top of that the problem that it may already have a style element that doesn't contain the "display:block" and you're looking at trouble.

So you could sanitize your input to make sure none of these is the case, but then you might as well make the whole thing more CSS-friendly (image spacers indeed! =). Actually, better than adding the inline style would be creating a class in your stylesheet that specifies display:block. But I'm getting ahead of myself, and probably of where you want to be.

A more robust solution than any involving a hand-rolled regex would be to write a filter, presumably using HTML::Parser or a subclass thereof, that does the job, along the following lines:

#!/usr/bin/perl # note, warnings are off because this shouldn't generate # 'em except where there is no "style" attribute on # image tags. use strict; use HTML::Parser; my $p=HTML::Parser->new( default_h => [ sub { print $_[0] }, 'text' ], start_h => [\&start_tag, 't +agname, attr, text']); $p->parse_file(*DATA); sub start_tag { my($tagname, $attr, $origtext) = @_; if ( ! ( $tagname eq "img") ) { print $origtext; return; } if ($attr->{style} !~/display:block/) { # avoid messy issues with other styles that may have been defined $attr->{style} = "display:block;". $attr->{style}; } print "<$tagname"; foreach ( keys %$attr) { print qq{ $_="} .$attr->{$_}.qq{"}; } print ">"; } __DATA__ <html> <head> <title>Boo</title> </head> <body bgcolor="#434343"> <h3>Hello</h3> <img src="witches.jpg"> <img src="macbeth.jpg" style="border: thick double #fcfcfc;"> <img src="foofaraw" style="width: 90"> <img src="cauldron.jpg" style="display:block"> <img src="fenny_snake.png"><span style="display: block">Hi there</sp +an> </body> </html>

I mistrust all systematizers and avoid them. The will to a system shows a lack of integrity -- F. Nietzsche