Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl convert url string to link

Tags:

regex

url

perl

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.

like image 911
shaneburgess Avatar asked Jan 26 '26 02:01

shaneburgess


1 Answers

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>";
like image 107
DVK Avatar answered Jan 28 '26 19:01

DVK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!