How to get the first subdomain with PHP?

六眼飞鱼酱① 提交于 2019-12-01 07:59:57
$domain = 'sub.dev.example.com';
$tmp = explode('.', $domain);
$subdomain = current($tmp);
print($subdomain);     // prints "sub"

This is another simple solution for the question.

echo array_shift((explode(".",$_SERVER['HTTP_HOST'])));

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;
    }
}

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' 
tasmaniski

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

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

Original link

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!