How can I selectively modify the src attributes of script tags in an HTML document using Perl?

寵の児 提交于 2019-12-11 02:21:37

问题


I need to write a regular expression in Perl that will prefix all srcs with [perl]texthere[/perl], like such:

 <script src="[perl]texthere[/perl]/text"></script> 

Any help? Thanks!


回答1:


Use a proper parser such as HTML::TokeParser::Simple:

#!/usr/bin/env perl

use strict; use warnings;
use HTML::TokeParser::Simple;

my $parser = HTML::TokeParser::Simple->new(handle => \*DATA);

while (my $token = $parser->get_token('script')) {
    if ($token->is_tag('script')
            and defined(my $src = $token->get_attr('src'))) {
            $src =~ m{^https?://}
                or  $token->set_attr('src', "[perl]texthere[/perl]$src");
    }
    print $token->as_is;
}

__DATA__
<script src="/js/text.text.js/"></script>

And at the same time, ignore scrs that begin with http, as such:

 <script src="https://websitewebsitewebsite"></script>

Output:

<script src="[perl]texthere[/perl]/js/text.text.js/"></script>

And at the same time, ignore scrs that begin with http, as such:

 <script src="https://websitewebsitewebsite"></script>



回答2:


Use the negative lookahead pattern (on the third line below):

s{
  (<script\s+src\s*=\s*[\'"])
  (?!https?://)
}{$1\[perl]texthere[/perl]}gsx;



回答3:


I am able to match any src=" except for http via: ^<script src="(?!(https:)).*$ Let me know if there are any issues and I'll fix it.

Try using: this website as a regex tutorial and this website to test regex.




回答4:


This should work:

 s{(?<=src=)(?!"https?)}{[perl]texthere[/perl]}

Test:

 my @olnk = ('<script src=/js/text.text.js/"></script>',
             '<script src="https://websitewebsitewebsite"></script>' );
 my @nlnk = map {
                  s{(?<=src=)(?!"https?)}{[perl]texthere[/perl]}; $_
                } @olnk;

Result:

 print join "\n", @nlnk;

 <script src=[perl]texthere[/perl]/js/text.text.js/"></script>
 <script src="https://websitewebsitewebsite"></script>

Regards

rbo



来源:https://stackoverflow.com/questions/11252314/how-can-i-selectively-modify-the-src-attributes-of-script-tags-in-an-html-docume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!