Portal Home > Knowledgebase > Articles Database > How to extract the domain name?


How to extract the domain name?




Posted by meshuge, 06-03-2009, 12:06 AM
I am looking for a regular expression that will extract the registered domain name given the host name. I noticed that some countries do not have 2nd level domains (e.g. Germany), some have 2nd level domains which are 3-letter long (e.g., US and Australia, ...), other have 2nd level domain names which are 2-letter long (Japan, UK, ...), etc. Here are some examples of what the regex should do: a.domain.com => domain.com a.b.domain.de => domain.de a.domain.co.jp => domain.co.jp a.b.c.domain.com.au => domain.com.au etc Thanks! Last edited by meshuge; 06-03-2009 at 12:14 AM.

Posted by foobic, 06-03-2009, 12:17 AM
You can't do this with a regexp alone - you need to get and maintain a list of valid tlds for comparison. You also need to decide on your policy for edge cases, like domain.au.com (technically a subdomain of au.com, but for most practical purposes a registered domain).

Posted by tuxguru, 06-03-2009, 05:41 AM
The above regex might work in most cases assuming domain names are at least 4 characters (some more assumptions are made, so may not work in all cases). $matches[2] will contain your required domain name. For testing, you can save the above code in a php file and run it from command line as follows: However for an accurate matching, you should store all TLDs and compare like foobic said. The authoritative list of currently existing TLDs in the root zone can be found at the IANA website at http://www.iana.org/domains/root/db/

Posted by mwatkins, 06-03-2009, 10:58 AM
Getting a list of valid second-level domains for TLD's that have a defined policy is... not easy. Basically you've got to check with each and every TLD for their current policy. This wiki page on Mozilla may be accurate enough for your purposes. https://wiki.mozilla.org/TLD_List



Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read
Test Hard disk Speed (Views: 721)
Cloudflare (Views: 757)
How is Jodohost? (Views: 705)


Language: