Split with this snippet a full domain name into sub-domain, domain and tld


PHP URL / domain name splitter ver. 1.00

released: 2006-09-11
There is no standard PHP function to extract the tld from an URL, parsing an URL with parse_url() will return the hostname and other URL information. If you need only the tld, for example to query the whois data of a given domain name, the following script should be usefull. To run this script you need a database with all tld's. Check the support link to the right and join the forum to get the database dump.

Viewed 14974 times

Rating: script rated with stars
 

Your banner at finalwebsites.com?
use the contact form for further information and prices.

<?php
$url_parts = parse_url("http://mail.finalwebsites.co.uk");
$domain = $url_parts['']
$res = mysql_query("SELECT tld FROM domain_info ORDER BY LENGTH(tld) DESC");
// "ORDER BY LENGTH(tld)" will give first the co.uk and then the uk
while ($arr = mysql_fetch_assoc($res)) {
    $tmp_tld = substr($domain, -strlen(".".$arr['tld']));
    if ($tmp_tld == ".".$arr['tld']) { // You found the tld
        $tld = ltrim($arr['tld'], ".");
        $domainLeft = substr($domain, 0, -(strlen($tld) + 1)); // It will left the whatever, without the extension and the .
        if (strpos($domainLeft, ".") === false) { // It hasn't a subdomain
            $subDomain = "";
            $finalDomain = $domainLeft;
        } else {
            $domain_parts = explode(".", $domainLeft);
            $finalDomain = array_pop($domain_parts); // select the domain and remove it from the array
            $subDomain = implode(".", $domain_parts); // a subdomain can more then one parts seperated with dot's
        }
        echo "The tld is: ".$tld."<br>";
        echo "the domain name is :".$finalDomain."<br />";
        echo "the subdomain is: ";
        echo (!empty($subDomain)) ? $subDomain : "n/a";
        echo "<br>";
        break;
    }
}
?>