How to get the first subdomain with PHP?

前端 未结 5 834
广开言路
广开言路 2020-12-11 23:10

I have a static domain of dev.example.com with wildcard subdomains like so *.dev.example.com.

I need to detect the name of the current wild

相关标签:
5条回答
  • 2020-12-11 23:20
    $domain = 'sub.dev.example.com';
    $tmp = explode('.', $domain);
    $subdomain = current($tmp);
    print($subdomain);     // prints "sub"
    
    0 讨论(0)
  • 2020-12-11 23:24

    Here's a little function that'll do the trick. Just stick $_SERVER['HTTP_HOST'] into the function and you should get what you want

    function getSubDomain ($domain) {
        $eDom = explode('.', $domain);
        return $eDom[0];
    }
    
    echo getSubDomain('sub.dev.example.com'); // echo 'sub' 
    
    0 讨论(0)
  • 2020-12-11 23:24

    From PHP 5.3 you can use strstr() with true parameter

    echo strstr('sub.dev.example.com', '.', true); //prints sub
    

    Original link

    0 讨论(0)
  • 2020-12-11 23:34

    This is another simple solution for the question.

    echo array_shift((explode(".",$_SERVER['HTTP_HOST'])));
    
    0 讨论(0)
  • 2020-12-11 23:34

    I think using parse_url function is much better approach:

    getUrlSubdomain($url){
        $urlSegments = parse_url($url);
        $urlHostSegments = explode('.', $urlSegments['host']);
    
        if(count($urlHostSegments) > 2) {
            return $urlHostSegments[0];
        }
        else{
            return null;
        }
    }
    
    0 讨论(0)
提交回复
热议问题