wasim beg
wasim beg

Reputation: 73

how to get only domain name from given URL in php

Suppose i have given URL, i want to get only domain name. How do i achieve this in Php.

    +----------------------+------------+
    | input                | output     |
    +----------------------+------------+
    | www.google.com       | google     |
    | www.mail.yahoo.com   | mail.yahoo |
    | www.mail.yahoo.co.in | mail.yahoo |
    | www.abc.au.uk        | abc        |
     www.subdoamin.domain.co.in     // output subdomain

I applied the follwing trick but fails when i have TLD like "co.uk"

     if(isset($project_detail_all[0]->d_name)) {
        $domain_name = $project_detail_all[0]->d_name ;
        $domain_name = explode('.', $domain_name);
        $count = count($domain_name);
        if (top_level_domains($domain_name[$count-1]) && 
            stristr($rss_url, $domain_name[$count-2])) {
            return  isValidXML($rss_url);
        } else {
            return  ['status'=>false , 'invalid_Domain'=>true];
        }
    } else {
        return  ['status'=>false , 'invalid_Domain'=>true];
    }

Kindly help me

Upvotes: 0

Views: 1364

Answers (2)

Bhaumik Pandhi
Bhaumik Pandhi

Reputation: 2673

please use regex to get only domain.

/.*?\.([A-z\d\.]+)(.co|.au)/s 

You can see my solution result here. green colored text is result of regex.

Use below code.

$urls = ['www.google.com','www.mail.yahoo.com','www.mail.yahoo.co.in','www.abc.au.uk','www.subdoamin.domain.co.in','abc.news18.co.in/abc.php'];
$result = [];
foreach($urls as $url){
   preg_match('/.*?\.([A-z\d\.]+)(.co|.au)/s',$url,$match);
   $result[] = $match[1];
}
echo '<pre>';print_r($result);

And you'll get result whatever you want.

Upvotes: 1

Kurt Van den Branden
Kurt Van den Branden

Reputation: 12934

What you are looking for is parse_url()

<?php

    $url = parse_url("http://abc.news18.co.in");
    //echo $url['host'];
    echo preg_replace("/^([a-zA-Z0-9].*\.)?([a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z.]{2,})$/", '$2', $url['host']); 

?>

Upvotes: 2

Related Questions