Alex Rivera | Logout

Get domain name (not subdomain) in php

Asked 2010-04-21T00:36:17.557
38

I have a URL which can be any of the following formats:

http://example.com
https://example.com
http://example.com/foo
http://example.com/foo/bar
www.example.com
example.com
foo.example.com
www.foo.example.com
foo.bar.example.com
http://foo.bar.example.com/foo/bar
example.net/foo/bar

Essentially, I need to be able to match any normal URL. How can I extract example.com (or .net, whatever the tld happens to be. I need this to work with any TLD.) from all of these via a single regex?

Edit
Report

2 Answers

16

My solution in https://gist.github.com/pocesar/5366899

and the tests are here http://codepad.viper-7.com/GAh1tP

It works with any TLD, and hideous subdomain patterns (up to 3 subdomains).

There's a test included with many domain names.

Won't paste the function here because of the weird indentation for code in StackOverflow (could have fenced code blocks like github)

answered 2013-04-11T20:30:57.967
5
$onlyHostName = implode('.', array_slice(explode('.', parse_url($link, PHP_URL_HOST)), -2));

Using https://subdomain.domain.com/some/path as example

parse_url($link, PHP_URL_HOST) returns subdomain.domain.com

explode('.', parse_url($link, PHP_URL_HOST)) then breaks subdomain.domain.com into an array:

array(3) {
  [0]=>
  string(5) "subdomain"
  [1]=>
  string(7) "domain"
  [2]=>
  string(3) "com"
}

array_slice then slices the array so only the last 2 values are in the array (signified by the -2):

array(2) {
  [0]=>
  string(6) "domain"
  [1]=>
  string(3) "com"
}

implode then combines those two array values back together, ultimately giving you the result of domain.com

Note: this will only work when end domain you're expecting only has one . in it, like something.domain.com or else.something.domain.net

It will not work for something.domain.co.uk where you would expect domain.co.uk

answered 2013-02-27T15:36:43.017

Your Answer