How to replace multiple words, each hashed with an alternative word, in an HTML attribute using a Perl regular expression?

I am writing an HTML obfuscator and I have a hash matching friendly names (from identifiers and classes) with obfuscation names (e.g. a, b, c, etc.). I'm having trouble getting a regular expression to do a replacement of something like

<div class="left tall">

from

<div class="a b">

If tags can only take one class, the regex will just be something like

s/(class|id)="(.*?)"/$1="$hash{$2}"/

How do I fix this to allow for multiple class names in quotation marks? Preferably, the solution should be compatible with Perl.

+3
source share
2 answers

I think I would do this:

s/  
    (class|id)="([^"]+)"
/   
    $1 . '="' . (
        join ' ', map { $hash{$_} } split m!\s+!, $2
    ) . '"'
/ex;
-1

. (. , 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>
+6

Source: https://habr.com/ru/post/1714131/


All Articles