get exect domain name in a string

Discussion in 'PHP' started by vOlLvEriNe, Feb 6, 2014.

  1. #1
    Hi all
    If I have many urls,
    mail.google.com.pk
    mail.google.com
    google.com
    google.com.pk

    how I get only google in output, please suggest me idea
     
    vOlLvEriNe, Feb 6, 2014 IP
  2. vOlLvEriNe

    vOlLvEriNe Member

    Messages:
    99
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #2
    vOlLvEriNe, Feb 6, 2014 IP
  3. sarahk

    sarahk iTamer Staff

    Messages:
    28,897
    Likes Received:
    4,555
    Best Answers:
    123
    Trophy Points:
    665
    #3
    so you just want the domain and you need a script that is smart enough to recognise a tld?
     
    sarahk, Feb 6, 2014 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    This is sorta ambiguous - do you need this to recognize any TLD, and only the domain itself? Note: a "domain" in this setting is not just the name "Google" - it's actually "Google.com"
    However, this code does what you want on the example above:
    
    <?php
    $domain_array = array('mail.google.com.pk','mail.google.com','google.com','google.com.pk');
    foreach($domain_array as $key => $value) {
       $tld_array = array('com','com.pk','net','org','me','co.uk','no','se');
       $url_ex = array_reverse(explode('.',$value));
       if (!in_array($url_ex[0],$tld_array)) {
         if (!in_array($url_ex[1].'.'.$url_ex[0],$tld_array)) {
           echo 'Couldn\'t find TLD';
         } else {
           echo $url_ex[2].PHP_EOL;
         }
       } else {
         echo $url_ex[1].PHP_EOL;
       }
    }
    ?>
    
    PHP:
    However, you will need to update the $tld_array to match more TLDs, if needed.
     
    PoPSiCLe, Feb 7, 2014 IP