Wednesday, May 11, 2011

How to Extract URL Fields in Perl Using Regex

$url = param('url');
print "url=$url<BR>\n";

# use m|...| so that we do not need to use a lot of "\/"
$url =~ m|(\w+)://([^/:]+)(:\d+)?/(.*)|;  

$protocol   = $1;
$domainName = $2;
$uri        = "/" . $4;

print "\$3=$3<BR>\n";

# Extract port number or default to 80
if ($3 =~ /:(\d+)/) { 
    $portNo = $1;
} else { 
    $portNo = 80;
}

# Print the extracted fields
print "protocol=$protocol<BR>\n"
    . "domainName=$domainName<BR>\n"
    . "portNo=$portNo<BR>\n"
    . "uri=$uri<BR>\n";

No comments: