Im looking for a method (or function) to strip out the domain.ext part of any URL thats fed into the function. The domain extension can be anything (.com, .co.uk, .nl, .whatever), and the URL thats fed into it can be anything from http://www.domain.com to www.domain.com/path/script.php?=whatever
Whats the best way to go about doing this?
I spent some time thinking about whether it makes sense to use a regular expression for this, but in the end I think not.
firstresponder's regexp came close to convincing me it was the best way, but it didn't work on anything missing a trailing slash (so http://example.com, for instance). I fixed that with the following:
'/\w+\..{2,3}(?:\..{2,3})?(?=[\/\W])/i'
, but then I realized that matches twice for urls like 'http://example.com/index.htm'. Oops. That wouldn't be so bad (just use the first one), but it also matches twice on something like this: 'http://abc.ed.fg.hij.kl.mn/', and the first match isn't the right one. :(A co-worker suggested just getting the host (via
parse_url()
), and then just taking the last two or three array bits (split()
on '.') The two or three would be based on a list of domains, like 'co.uk', etc. Making up that list becomes the hard part.There is only one correct way to extract domain parts, it's use Public Suffix List (database of TLDs). I recomend TLDExtract package, here is sample code:
Here are a couple simple functions to get the root domain (example.com) from a normal or long domain (test.sub.domain.com) or url (http://www.example.com).
You can use parse_url() to do this:
In this example, $domain should contain example.com, irrespective of it having www or not. It also works for a domain such as .co.uk
parse_url turns a URL into an associative array:
Solved this...
Say we're calling dev.mysite.com and we want to extract 'mysite.com'
Works with mysite.co.uk too so should work everywhere :)