fubar'd
fubar'd

Reputation: 21

Replacing URLs in Strings - 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 :)

Upvotes: 2

Views: 1313

Answers (4)

Tilo
Tilo

Reputation: 33732

if you also have multiple input files, and need to consistently change strings in all input files, this script can come in handy:

http://unixgods.org/~tilo/replace_string/

Upvotes: 0

David Precious
David Precious

Reputation: 6553

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.

Upvotes: 2

erickb
erickb

Reputation: 6309

Try using URI::Find.

Upvotes: 6

Leonardo Herrera
Leonardo Herrera

Reputation: 8406

URI::URL is your friend.

#!/usr/bin/perl
use strict;
use URI::Split qw(uri_split uri_join);
my ($scheme, $auth, $path, $query, $frag) = uri_split($uri);
my $uri = uri_join($scheme, $auth, $path, $query, $frag);

Upvotes: 1

Related Questions