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.
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>";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With