Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP REGEX: Get domain from URL

Tags:

regex

url

php

dns

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!

like image 408
Adam Halasz Avatar asked Aug 09 '10 17:08

Adam Halasz


4 Answers

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);
like image 163
cletus Avatar answered Nov 10 '22 19:11

cletus


I use:

$domain = parse_url('http://' . str_replace(array('https://', 'http://'), '', $url), PHP_URL_HOST);

Because parse_url doesn't return host key when schema is missing in $url.

like image 42
Marcin Żurek Avatar answered Nov 10 '22 18:11

Marcin Żurek


$tmp = parse_url($url);
$url = $tmp['host']
like image 2
turbod Avatar answered Nov 10 '22 19:11

turbod


This is like the regex from theraccoonbear but with support for HTTPS domains.

if (preg_match('/https?:\/\/([^\/]+)\//i', $target_string, $matches)) {
  $domain = $matches[1];
}
like image 2
fnkr Avatar answered Nov 10 '22 18:11

fnkr