in reply to Remove all html tag Except 'sup'
I second marto and others. Don't use regexes on HTML unless you know the HTML in questions intimately and know regular expressions well. This lucky coincidence is rare in the wild. Here's a somewhat flexible example with HTML::TokeParser.
use strict; use warnings; use HTML::TokeParser; my @tags = @ARGV; @tags || die "Give a list of tags to retain.\n"; my %keep = map { lc($_) => 1, lc("/$_") => 1 } @tags; my $p = HTML::TokeParser->new(\*DATA); while ( my $t = $p->get_token ) { if ( $t->[0] =~ /S|E/ and $keep{$t->[1]} ) { print $t->[-1]; } elsif ( $t->[0] eq 'T' ) { print $t->[1]; } } __DATA__ <div> <h1>Bang!<sup>1</sup></h1> <p>Did <i>italic</i> and <a href="/uri">link with <b>bold</b> inside it</a>.</p> <a href="/top-level">naked link</a> <p><i>The</i> <b>content</b> of the body <sup>element</sup> is displayed in your <span>browser</span>.</p> </div>
And because I have it lying around, here is the obverse -- a tag stripper -- with XML::LibXML.
use warnings; use strict; use XML::LibXML; my @strip = @ARGV; @strip || die "Give a list of tags to strip.\n"; my $parser = XML::LibXML->new(); $parser->line_numbers(1); my $raw = join '', <DATA>; my $doc = $parser->parse_html_string($raw); my $root = $doc->documentElement(); for my $strip ( @strip ) { for my $node ( $root->findnodes("//$strip") ) { my $fragment = $doc->createDocumentFragment(); $fragment->appendChild($_) for $node->childNodes; $node->replaceNode($fragment); } } print $doc->serialize(1); __END__ <div> <h1>Bang!<sup>1</sup></h1> <p>Did <i>italic</i> and <a href="/uri">link with <b>bold</b> inside it</a>.</p> <a href="/top-level">naked link</a> <p><i>The</i> <b>content</b> of the body <sup>element</sup> is displayed in your <span>browser</span>.</p> </div>
|
|---|