1

我想将<a>标签更改为 HTML 文本(不是完整的 HTML 文档)中的外部链接。然而,如果模式在同一行字符串中多次出现,则此 Perl 程序无法替换模式。

这是一个示例程序:

use strict;
use warnings;

my $baseURL = "https://example.com";
my $input = <<'END';
<ul>
    <li><a href="https://www.amazon.com">Amazon</a></li>
    <li>
        <!-- Keep it in one line. -->
        <a href="https://www.google.com.tw">Google</a> and <a href="https://tw.yahoo.com">Yahoo</a> and <a href="https://duckduckgo.com">DuckDuckGo</a>
    </li>
</ul>
END

# Replace external links globally.
$input =~ s{<a href=\"([^"]+)\">(.+)</a>}{
    # Skip local URIs.
    substr($1, 0, 4) ne "http" ? "<a href=\"$1\">$2</a>"
    # Skip links in same domain.
    : index($1, "$baseURL") >= 0 ? "<a href=\"$1\">$2</a>"
    # Disable search engines from following links.
    : "<a href=\"$1\" target=\"_blank\" rel=\"noopener nofollow\">$2</a>"}ge;

# Print modified input to STDOUT.
print $input;
4

1 回答 1

2

(.+)是贪婪的,把一切都抓到最后</a>。尝试(.+?)改用。

于 2021-06-22T07:11:42.857 回答