Get a domain from a URL

7 October 2009 17:11

Been looking for a function in ColdFusion to get the root domain from a url. There are a few but none actually cope with the many combinations. This function by no means copes with every combination however it does cover quite a lot. Comments inline indicate which domains the rules handle.


<cffunction name="getRootDomain" returntype="string" output="no" hint="Take a URL and get the domain from it.">
<cfargument name="url" type="string" required="true">
<cfset var dots = listLen(arguments.url,".")>
</cfset><cfset var domain = "">
</cfset><cfset host = arguments.url>
<!--- host.com, host.biz, host.ly --->
<cfif dots eq 2>
<cfset domain = host>
</cfset></cfif>
<cfif dots eq 3>
<!--- www.host.com, sub.host.com, www.host.mobi, www.host.ly, del.icio.us --->
</cfif><cfif listfirst(host,".") eq "www" or
((len(listgetat(host,3,".")) eq 3 or len(listgetat(host,3,".")) eq 2) and len(listgetat(host,"2",".")) gte 3)>
<cfset domain = listdeleteat(host,1,".")>
</cfset></cfif>
<!--- host.co.uk, host.com.za --->
<cfif (len(listgetat(host,3,".")) eq 2 and (len(listgetat(host,2,".")) eq 2) or len(listgetat(host,2,".")) eq 3)>
<cfset domain = host>
</cfset></cfif>
<cfif dots eq 4>
<!--- www.host.ltd.uk, www.host.co.uk --->
</cfif><cfif len(listgetat(host,4,".")) eq 2 and (len(listgetat(host,3,".")) eq 2 or len(listgetat(host,3,".")) eq 3)>
<cfset domain = listdeleteat(host,1,".")>
</cfset></cfif>
<!--- www.sub.host.com, sub.sub.host.com --->
<cfif len(listgetat(host,4,".")) eq 3 and len(listgetat(host,4,".")) gte 3>
<cfset domain = listdeleteat(listdeleteat(host,1,"."),1,".")>
</cfset></cfif>
<cfif dots eq 5>
<!--- sub.sub.host.co.uk, www.sub.host.co.uk, www.sub.host.com.za --->
</cfif><cfif len(listgetat(host,5,".")) eq 2 and (len(listgetat(host,4,".")) eq 2 or len(listgetat(host,4,".")) eq 3)>
<cfset domain = listdeleteat(listdeleteat(host,1,"."),1,".")>
</cfset></cfif>
<cfreturn domain />
</cfset></cfargument></cffunction>

Filed: Technology // Tagged: ,

You can follow any responses to this entry through the RSS 2.0 feed.

You can leave a comment or leave a trackback from your own site.

One Response to “Get a domain from a URL”

  1. Brad Wood on October 28th, 2009 at 3:40 am

    The Java class java.net.URL. You can create it directly with createObject and it will parse any part of a URL out for you.

    http://www.codersrevolution.com/index.cfm/2008/6/27/Fun-with-javanetURL

Leave a Reply

 
What's ianteresting?   •   Twitter   •   About   •   Contact
©2012 Ian Winter. All Rights Reserved.   •   Powered by WordPress   •   Hosted at Memset