PHP REGEX: Get domain from URL

Viewed 32640

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!

9 Answers

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

if (preg_match('/https?:\/\/([^\/]+)\//i', $target_string, $matches)) {
  $domain = $matches[1];
}

I think the following regexp might answers your question.

This diagram explains how it works, or rather why it works :-)

$regexp = '/.*\/\/([^\/:]+).*/';

// www.stackoverflow.com
echo preg_replace($regexp, '$1', 'http://www.stackoverflow.com/questions/ask');

// google.de
echo preg_replace($regexp, '$1', 'http://google.de/?q=hello');

// it works for the other input tests too ;-)
Related