use*_*147 3 html css obfuscation perl
我正在写一个HTML混淆器,我有一个哈希将用户友好名称(ids和类)与模糊名称(如a,b,c等)相关联.我很难想出一个正则表达式来完成替换之类的东西
<div class="left tall">
Run Code Online (Sandbox Code Playgroud)
同
<div class="a b">
Run Code Online (Sandbox Code Playgroud)
如果标签只能接受一个类,则regexp就像是一样
s/(class|id)="(.*?)"/$1="$hash{$2}"/
Run Code Online (Sandbox Code Playgroud)
我应该如何纠正这个问题来解释引号内的多个类名?优选地,该解决方案应该是Perl兼容的.
你不应该首先使用正则表达式.你试图用一个正则表达式做太多(参见你能提供一些为什么难以用正则表达式解析XML和HTML的例子吗?).你需要的是一个HTML解析器.请参阅您是否提供了使用您喜欢的解析器解析HTML的示例?例如,使用各种解析器.
看看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>
Run Code Online (Sandbox Code Playgroud)