0

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

Andreas
  • 23,610
  • 6
  • 30
  • 62
wasim beg
  • 73
  • 13

2 Answers2

2

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']); 

?>
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
1

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.

Bhaumik Pandhi
  • 2,655
  • 2
  • 21
  • 38
  • 1
    It was not working before, now I've changed my answer and regex so it will work now, please open new updated link and you can get idea, – Bhaumik Pandhi May 19 '17 at 11:53