How to get subdoman name from full url

Discussion in 'PHP' started by Om ji Kesharwani, Aug 22, 2010.

  1. #1
    Om ji Kesharwani, Aug 22, 2010 IP
  2. monfis

    monfis Well-Known Member

    Messages:
    1,476
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    160
    #2
    monfis, Aug 22, 2010 IP
  3. MyVodaFone

    MyVodaFone Well-Known Member

    Messages:
    1,048
    Likes Received:
    42
    Best Answers:
    10
    Trophy Points:
    195
    #3
    Throw this into a test.php file, I think this is what you want ?

    <?php 
    
    $domain = "http://www.this-subdomain.mydomain.com";
    
    $regex = "#^([a-z0-9][a-z0-9\-]{1,63})\.[a-z\.]{2,63}$#i";
    
    $domain = str_replace('http://', '', $domain);
    $domain = str_replace('www.', '', $domain);
    
    preg_match($regex, $domain, $matches);
    
    echo "If it exist remove the http:// & www. to make the domain : ", $matches[0]," <br />"; 
    echo "We then searched for the subDomain, and found : ", $matches[1]," <br />"; 
    
    ?>
    PHP:
    Out-Put:
    
    If it exist remove the http:// & www. to make the domain : this-subdomain.mydomain.com
    We then searched for the subDomain, and found : this-subdomain 
    
    Code (markup):
    So you echo $matches[1] for subDomain
     
    Last edited: Aug 22, 2010
    MyVodaFone, Aug 22, 2010 IP
  4. johirshikder

    johirshikder Peon

    Messages:
    1
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    subdomain.mydomain.com


    subdomain.mydomain
    and
     
    johirshikder, Aug 22, 2010 IP
  5. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #5
    <?php
    $url = 'http://subdomain.mydomain.com';
    
    $pattern = '(?:http://)?'; //protocol (optional)
    
    $pattern .= '(?:www\.)?'; //www. (optional)
    
    $pattern .= '([^\.]+)'; //subdomain
    
    $pattern .= '\.[^\.]+\.'; //domain
    
    $pattern .= '[^ ]+'; //tld
    
    preg_match("~{$pattern}~i", $url, $a);
    
    echo htmlspecialchars($a[1]);
    ?>
    PHP:
    or simplified:

    <?php
    $url = 'http://subdomain.mydomain.com';
    
    $pattern = '(?:http://)?'; //protocol (optional)
    
    $pattern .= '(?:www\.)?'; //www. (optional)
    
    $pattern .= '([^\.]+)'; //subdomain
    
    $pattern .= '[^ ]+'; //the rest...
    
    preg_match("~{$pattern}~i", $url, $a);
    
    echo htmlspecialchars($a[1]);
    ?>
    PHP:
     
    Last edited: Aug 22, 2010
    danx10, Aug 22, 2010 IP
  6. danx10

    danx10 Peon

    Messages:
    1,179
    Likes Received:
    44
    Best Answers:
    2
    Trophy Points:
    0
    #6
    Also take alook at:

    parse_url($url, PHP_URL_HOST);
    PHP:
     
    danx10, Aug 22, 2010 IP