PHP's parse_url() has a host field, which includes the full host. I'm looking for the most reliable (and least costly) way to only return the domain and TLD.
Given the examples:
- http://www.google.com/foo, parse_url() returns www.google.com for host
- http://www.google.co.uk/foo, parse_url() returns www.google.co.uk for host
I am looking for only google.com or google.co.uk. I have contemplated a table of valid TLD's/suffixes and only allowing those and one word. Would you do it any other way? Does anyone know of a pre-canned valid REGEX for this sort of thing?
Best Answer
How about something like that?
Will extract the domain name using the classic
parse_url
and then look for a valid domain without any subdomain (www being a subdomain). Won't work on things like 'localhost'. Will return false if it didn't match anything.// Edit:
Try it out with:
And it should return:
Of course, it won't return anything if it doesn't get through
parse_url
, so make sure it's a well-formed URL.// Addendum:
Alnitak is right. The solution presented above will work in most cases but not necessarily all and needs to be maintained to make sure, for example, that their aren't new TLD with .morethan6characters and so on. The only reliable way of extracting the domain is to use a maintained list such as http://publicsuffix.org/. It's more painful at first but easier and more robust on the long-term. You need to make sure you understand the pros and cons of each method and how it fits with your project.