PHP preg_match hostname and domain from FQDN

On February 11, 2010, in How-to, Scripting, by Cubert aka (Cube Dweller)

How to get the hostname and the domain name from FQDN in PHP

This sound easy right? So easy that you would think it would be all over the internet as an example on how to parse host names from domain names. Wrong…. I spent a hour one day looking everywhere and all I found was parsing a URL. Well my needs go deeper I need to do a quick split of host name from domain name not matter how long or nested the domain names were.

There are a bunch of places that give you the same old PHP preg_match examples as found on www.php.net,   “How to parse the domain name from a URL.”

But lets say I want both the host name and the domain name? If you know anything about FQDN then you know that up to the first “.” is host name and everything else is sub domain, domain and root.

Sometimes your going to have a FQDN that = myname.mysub.mysecondsub.mydomain.root

You want to get “myname” & “mysub.mysecondsub.mydomain .root”

So here is how we do it…


//if host needs to be striped from a URL
preg_match('@^(?:http://)?([^/]+)@i', "http://barfly.beaners.bobbers.mybalistics.net/index.html", $matches);
$host = $matches[1];

//else make $host your FQDN and skip the above segment
preg_match("/^(.*?)\.(.*)/", $host, $rest);
echo "My name is" .$rest[1]. "
";
echo "My domain is" .$rest[2]. "
";

I hope this helps someone out there spending hours looking for the right expression.

Tagged with:
 

Leave a Reply