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

Please help.

2 Answers

0 votes
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
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

0 votes
1 answer 1.1k views
asked Oct 4, 2021 in General by Tester Testee (220 points)
+1 vote
1 answer 2.2k views
0 votes
1 answer 2.9k views
0 votes
1 answer 1.8k views
0 votes
0 answers 689 views
asked Oct 4, 2021 in General by anonymous
+1 vote
1 answer 1.6k views
...