I currently have a perl script that imports HTML and converts it to plain text. I am using HTML::TagFilter to remove all the HTML tags and it is working almost perfectly except we’ve run into one issue. When the HTML contains non-stand HTML tags such as the “caption” in the example input below those tags aren’t being removed:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam pulvinar, odio ut gravida fringilla, tellus mi ultrices felis, quis porta lacus sem ut lacus. Vestibulum massa justo, tristique id aliquet in, dapibus eu leo. Nam sapien risus, dictum et porttitor quis, egestas quis dui. Ut nec nisl felis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
<a href="http://www.domain.com/image.jpg"><img class="sample-image-class" title="Sample Title" src="http://www.domain.com/image.jpg" alt="Sample Alt" width="225" height="300" /></a>Sample Caption
In hac habitasse platea dictumst. Duis imperdiet bibendum dolor ut ullamcorper. Suspendisse dui erat, facilisis sed aliquet non, elementum eu urna. Donec non nisi vel augue gravida imperdiet sed id tortor. Maecenas ullamcorper velit non dui imperdiet hendrerit.
What I need help with is a simple Perl regex to remove this content completely. I’ve tried a bunch of different approaches but nothing seems to be working. What I’m looking for is something like the following which would find and remove all occurrences of non-standard HTML tags using brackets []:
$text =~ s/[(\w)+](.*)[\/(\w)+]//g;
I’m hoping it is a simple exercise for someone who is better at regex than I am.
Thanks in advance for your help!
You have to escape brackets because they have special meaning within regular expressions. Assuming that all attributes will be double-quoted with no double quotes inside them, the following should work.