我正在尝试从 HTML 文件中删除未使用的跨度(即那些没有属性的跨度),并且已经用其他正则表达式清理了我不需要的所有属性。
我的正则表达式有问题,没有选择要删除的正确的开始和结束标签对。
my $a = 'a <span>b <span style="color:red;">c</span> d</span>e';
$a =~ s/<span\s*>(.*?)<\/span>/$1/g;
print "$a\
returns
a b <span style="color:red;">c d</span>e
但我想让它回来
a b <span style="color:red;">c</span> de
帮助表示赞赏。
Try HTML::解析器:
#!/usr/bin/perl
use strict;
use warnings;
use HTML::Parser;
my @print_span;
my $p = HTML::Parser->new(
start_h => [ sub {
my ($text, $name, $attr) = @_;
if ( $name eq 'span' ) {
my $print_tag = %$attr;
push @print_span, $print_tag;
return if !$print_tag;
}
print $text;
}, 'text,tagname,attr'],
end_h => [ sub {
my ($text, $name) = @_;
if ( $name eq 'span' ) {
return if !pop @print_span;
}
print $text;
}, 'text,tagname'],
default_h => [ sub { print shift }, 'text'],
);
$p->parse_file(\*DATA) or die "Err: $!";
$p->eof;
__END__
<html>
<head>
<title>This is a title</title>
</head>
<body>
<h1>This is a header</h1>
a <span>b <span style="color:red;">c</span> d</span>e
</body>
</html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)