Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing URLs in Strings - Perl

Tags:

url

perl

I have a bunch of strings that have URLs in them and I need to remove the URL and replace it with a different one. The only way I can think of to do it is with split:

($start, $url, $end) = split(/:/);

But I don't think this is the right way to go about it, because if the url is at the start or end of the string it won't work properly.

Any ideas greatly appreciated :)

like image 925
fubar'd Avatar asked Dec 07 '25 06:12

fubar'd


2 Answers

Try using URI::Find.

like image 69
erickb Avatar answered Dec 09 '25 19:12

erickb


The already-suggested URI::Find looks to be a good bet.

Alternatively, Regexp::Common can provide suitable URLs to match URLs, for instance:

use Regexp::Common qw(URI);
my $string = "Some text, http://www.google.com/search?q=foo and http://www.twitter.com/";
$string =~ s{$RE{URI}}{http://stackoverflow.com/}g;

The above would replace both the URLs with http://stackoverflow.com/ as an example.

like image 45
David Precious Avatar answered Dec 09 '25 20:12

David Precious



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!