我正在编写一个 HTML 混淆器,并且我有一个将用户友好名称(ID 和类)与混淆名称(如 a、b、c 等)相关联的散列。我在想出一个正则表达式来完成替换类似
的东西时遇到了麻烦<div class="left tall">
与
<div class="a b">
如果标签只能接受一个类,则正则表达式将简单地类似于
s/(class|id)="(.*?)"/$1="$hash{$2}"/
我应该如何更正此问题以说明引号内的多个类名?最好,该解决方案应该与 Perl 兼容。
最佳答案
首先您不应该为此使用正则表达式。您试图用一个正则表达式做太多事情(请参阅 Can you provide some examples of why it is hard to parse XML and HTML with a regex? 了解原因)。您需要的是一个 HTML 解析器。参见 Can you provide an example of parsing HTML with your favorite parser?有关使用各种解析器的示例。
看看HTML::Parser
.这是一个可能不完整的实现:
#!/usr/bin/perl
use strict;
use warnings;
use HTML::Parser;
{
my %map = (
foo => "f",
bar => "b",
);
sub start {
my ($tag, $attr) = @_;
my $attr_string = '';
for my $key (keys %$attr) {
if ($key eq 'class') {
my @classes = split " ", $attr->{$key};
#FIXME: this should be using //, but
#it is only availble starting in 5.10
#so I am using || which will do the
#wrong thing if the class is 0, so
#don't use a class of 0 in %map , m'kay
$attr->{$key} = join " ",
map { $map{$_} || $_ } @classes;
}
$attr_string .= qq/ $key="$attr->{$key}"/;
}
print "<$tag$attr_string>";
}
}
sub text {
print shift;
}
sub end {
my $tag = shift;
print "</$tag>";
}
my $p = HTML::Parser->new(
start_h => [ \&start, "tagname,attr" ],
text_h => [ \&text, "dtext" ],
end_h => [ \&end, "tagname" ],
);
$p->parse_file(\*DATA);
__DATA__
<html>
<head>
<title>foo</title>
</head>
<body>
<span class="foo">Foo!</span> <span class="bar">Bar!</span>
<span class="foo bar">Foo Bar!</span>
This should not be touched: class="foo"
</body>
</html>
关于html - 如何使用 Perl 正则表达式替换 HTML 属性中的多个单词,每个单词散列为一个替代单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1217068/