0 votes
2.3k views
asked in General by
edited
How is it possible to extract a domain name (only) from a url input?

Please help.

2 Answers

0 votes
answered by
 
Best answer
Easiest is to use the regx

preg_match("/^(http:\/\/)?([^\/]+)/i", preg_replace( "#^[^:/.]*[:/]+#i", "", preg_replace( "{/$}", "", urldecode($resource_url))), $domain_data);

$website_domain_only = strtolower(preg_replace('#^www\.(.+\.)#i', '$1', $domain_data[2]));

echo $website_domain_only;

OR

You can also use the builtin method which is slow. Wrapped it as a function below.

echo url_to_domain($your_url_here);

function url_to_domain($url)
{
    $host = @parse_url($url, PHP_URL_HOST);

    if (!$host)
        $host = $url;

    if (substr($host, 0, 4) == "www.")
        $host = substr($host, 4);

    return $host;
}
0 votes
answered by
function cleanURL($url)
                    {
                        $url = preg_replace("/(^(http(s)?:\/\/|www\.))?(www\.)?([a-z-\.0-9]+)/","$5", trim($url));
                        if(preg_match("/^([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,6})/", $url, $domain)){
                          return $domain[1];
                        }
                        else return "not valid domain or subdomain".$url;
                      }

Related questions

+1 vote
1 answer 1k views
0 votes
1 answer 1.6k views
0 votes
1 answer 592 views
+1 vote
1 answer 6.6k views
+1 vote
1 answer 366 views
...