Replacing URLs in Strings - Perl
I have a bunch of strings that have URLs in them and I need to remove the U开发者_运维技巧RL 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 :)
Try using URI::Find.
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.
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);
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/
精彩评论