2009-08-01 1 views
3

나는 HTML obfuscator를 작성 중이며, (a, b, c와 같은) 난독 화 된 이름에 사용자 친화적 인 이름 (클래스 및 클래스)을 연관시키는 해쉬를 가지고있다. 태그는 하나 개의 클래스를 받아 들일 수 있다면 문제가Perl 정규식을 사용하는 HTML 속성에서 대체 단어로 해시 된 여러 단어를 어떻게 바꿀 수 있습니까?

<div class="a b"> 

<div class="left tall"> 

같은 대체 뭔가를 달성하기위한 정규 표현식을 세우는 데, 정규 표현식은 단순히

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

따옴표 안에 여러 클래스 이름이있는 경우 어떻게 수정해야합니까? 가장 좋은 해결책은 Perl과 호환 가능해야합니다.

+0

'left'와 'tall'은 'a'와 'b'처럼 혼란 스러울 수도 있습니다. –

답변

-1

는 내가이 작업을 수행 할 것 같아요 당신은 처음에 이것에 대한 정규식을 사용하지 않아야

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

HTML 텍스트에 class = "foo"가 포함 된 경우 어떻게합니까? 단일 정규식/대체는 재귀 적으로 구조화 된 데이터와 잘 섞이지 않습니다. –

6

. 하나의 정규식으로 너무 많은 것을하려고합니다 (이유는 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> 
관련 문제