Thursday, April 8, 2010

extract domain name from the url using regular expression

Question: How to extract domain name from a url using regular expressions

Answer:

preg_match('@^(?:http://)?([^/]+)@i',"http://blogger.com", $matches);
$host = $matches[1];

// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
echo "domain name is: {$matches[0]}\n";

The output is

domain name is: blogger.com

No comments:

Post a Comment