Escape characters in URLs

02 Jun 2007

You want to escape characters from a string that will be passed as parameter of a URL.

sub escape_uri {
  my $s = shift;
  $s =~s/([^a-zA-Z0-9_\-. ])/uc sprintf("%%%02x",ord($1))/eg;
  $s =~ tr/ /+/;
  return $s;
}

Or even better with URI::Escape:

use URI::Escape;
my $uri = uri_escape($string)

To unescape use:

$string =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;