如何使用Perl正则表达式去除未使用的,嵌套的HTML span标记? [英] How can I remove unused, nested HTML span tags with a Perl regex?

查看:116
本文介绍了如何使用Perl正则表达式去除未使用的,嵌套的HTML span标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从HTML文件中删除未使用的跨度(即没有属性的跨度),已经清除了我不想使用其他正则表达式的所有属性。



我遇到了一个问题,我的正则表达式没有选择正确的一对开始和结束标签来移除。

  my $ a ='a< span> b< span style =color:red;> c< / span> d< /跨度> E; 
$ a =〜s /< span \s *>(。*?)< \ / span> / $ 1 / g;
print$ a \

退货

  ab< span style =color:red;> c d< / span> e 

但我希望它返回

  ab   


解决方案

试试 HTML :: Parser

 #!/ usr / bin / perl 

使用strict;
使用警告;

使用HTML :: Parser;

my @print_span;
my $ p = HTML :: Parser->新(
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)或者死掉Err:$!;
$ p-> eof;

__END__
< html>
< head>
< title>这是一个标题< / title>
< / head>
< body>
< h1>这是一个标题< / h1>
a< span> b< span style =color:red;> c< / span> d< / span> e
< / body>
< / html>


I'm trying to remove unused spans (i.e. those with no attribute) from HTML files, having already cleaned up all the attributes I didn't want with other regular expressions.

I'm having a problem with my regex not picking the correct pair of start and end tags to remove.

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

but I want it to return

a b <span style="color:red;">c</span> de

Help appreciated.

解决方案

Try 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>

这篇关于如何使用Perl正则表达式去除未使用的,嵌套的HTML span标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆