shaneburgess
shaneburgess

Reputation: 15882

Perl convert url string to link

I am looking for a way to find a url in a string and convert it to a link.

The url may be anywhere in the string (beginning, middle, or the end).

Regex is preferred but CPAN modules are welcome.

Upvotes: 2

Views: 2878

Answers (3)

justintime
justintime

Reputation: 3631

You can use Regexp::Common to find the string and then do a substitution to make it into a links. In the absence of any thing else I have used the URL as the link text.

    use Regexp::Common "URI";
    my $string="Some text containing http://stackoverflow.com/questions/4587876/perl-convert-url-string-to-link in middle" ;

    $string =~    s( ($RE{URI}{HTTP}) )
                  (<a href="$1">$1</a>)gx  ;

    print $string ;

Upvotes: 4

DVK
DVK

Reputation: 129403

Most common solution is Regexp::Common (no pun intended). You need to use {-keep} version as shown below to keep the match (in $1, obviously)

use Regexp::Common qw /URI/;

while (<>) {
    /$RE{URI}{HTTP}{-keep}/ and print "<A HREF="$1">My Link Name</A>";
} 

As is hopefully obvious, the above example only finds 1 link per line. Fixing for more is left as exercise for the user.


Another option is Schwern's URI::Find. From POD example:

use CGI qw(escapeHTML);
use URI::Find;
my $finder = URI::Find->new(sub {
    my($uri, $orig_uri) = @_;
    return qq|<a href="$uri">$orig_uri</a>|;
});
$finder->find(\$text, \&escapeHTML);
print "<pre>$text</pre>";

Upvotes: 6

Hugmeir
Hugmeir

Reputation: 1259

use strict;
use warnings;
use 5.010;
use utf8;
use Regexp::Common qw /URI/;

my $string_with_url = <<'END_STRING';
This is an url to your question:
http://stackoverflow.com/questions/4587876/perl-convert-url-string-to-link
END_STRING

say $string_with_url;

$string_with_url =~ s/($RE{URI}{HTTP})/get_link()/eg;

say $string_with_url;

sub get_link {
    return <<'END_LINK';
        _____________¶¶¶¶¶¶¶¶¶¶¶¶¶¶
        ___________¶¶6666555666666¶¶¶
        __________¶¶6666555555556666¶¶
        ___¶¶¶__¶¶¶¶116666556611¶¶666¶¶¶¶
        __¶¶cc¶¶§§§¶¶¶11111111¶¶¶¶¶6¶¶cc¶¶
        __¶¶cc¶¶¶§§§§¶¶¶¶¶¶¶¶¶¶§§§¶¶¶¶cc¶¶
        __¶¶ssc¶¶¶¶§§§§§§§§§§§§§§¶¶¶¶css¶¶
        __¶¶ss¶¶§§¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶§§§¶¶ss¶¶
        ____¶¶ss¶¶ss¯¯¯¯ssss¯¯¯¯ss¶¶ss¶¶
        ______¶¶ssss__¶¶cccc¶¶__ssss¶¶
        ______¶¶¶ssscc¶¶cccc¶¶ccss¶¶¶¶
        _____¶¶££¶¶sssccccccccss¶¶¶££¶¶
        ____¶¶££££¶¶ss¶¶cccsss¶¶¶£££¶¶¶¶¶
        __¶¶¯¯¶¶¶¶¶¶¶¶¯¯¶¶¶¶¶¶¶££££¶¶¶ss¶¶
        __¶¶____________¶¶££££££££¶¶ssss¶¶
        __¶¶¯¯$$$$$$$$¯¯¶¶£££££££££¶¶¶cc¶¶
        __¶¶__$$ƒƒƒƒ$$__¶¶£££££££¢¢¶¶ccc¶¶
        __¶¶¯¯$$ƒƒƒƒ$$¯¯¶¶¢¢¢¥¥¢¢£££¶¶cc¶¶
        __¶¶___$$ƒƒ$$___¶¶££££££££¶¶¶¶¶¶¶
        ____¶¶__$$$$__¶¶££££££¶¶¶¶¥¥¶¶¶
        ______¶¶____¶¶¶¶¶¶¶¶¶¶¥¥¥¥¥¶¶¶
        ________¶¶¶¶¶¶¶¶¶¥¥¥¥¥¥¥¶¶¶¶
        ____________¶¶¶¶¶¶¶¶¶¶¶¶
END_LINK
}

Upvotes: 5

Related Questions