views:

157

answers:

6

What I want


I want to get from a URL the domain part so from http://example.com/ -> example.com

Examples:


+----------------------------------------------+-----------------------+
| input                                        | output                |
+----------------------------------------------+-----------------------+
| http://www.stackoverflow.com/questions/ask   | www.stackoverflow.com |
| http://validator.w3.org/check                | validator.w3.org      |
| http://www.google.com/?q=hello               | www.google.com        |
| http://google.de/?q=hello                    | google.de             |
+----------------------------------------------+-----------------------+

I found some related questions in stackoverflow but none of them was exactly what I was looking for.

Thanks for any help!

A: 

Here's my quick and dirty solution.

http://([^/]+).*

I haven't tested it, but it should grab anything between the http:// and the first slash.

haydenmuhl
+1  A: 

Assumes that http:// prefixes everything.

$tmp = explode("/", $url);
$domain = $tmp[2];
Josh K
heh, most out-of-the-box solution :-)
gnud
+8  A: 

There's no need to use a regex for this. PHP has an inbuilt function to do just this. Use parse_url():

$domain = parse_url($url, PHP_URL_HOST);
cletus
+1  A: 

parse_url is already a PHP function, no need to duplicate it. http://php.net/manual/en/function.parse-url.php

Paul Tomblin
A: 
if (preg_match('/http:\/\/([^\/]+)\//i', $target_string, $matches)) {
  $domain = $matches[1];
}
theraccoonbear
+1  A: 
$tmp = parse_url($url);
$url = $tmp['host']
turbod