我正在尝试从 HTML 文件中删除未使用的跨度(即没有属性的跨度),已经用其他正则表达式清除了我不需要的所有属性。
我的正则表达式没有选择要删除的正确的开始和结束标记对时出现问题。
my $a = 'a <span>b <span style="color:red;">c</span> d</span>e';
$a =~ s/<span\s*>(.*?)<\/span>/$1/g;
print "$a\
返回
a b <span style="color:red;">c d</span>e
但我希望它返回
a b <span style="color:red;">c</span> de
感谢帮助。
最佳答案
尝试 HTML::Parser :
#!/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>
关于html - 如何使用 Perl 正则表达式删除未使用的嵌套 HTML span 标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/667130/