Skip to main content
2 of 2
Added links to docs
Aamir
  • 5.4k
  • 2
  • 31
  • 47

You can use parse_url to get everything after the http:// and https:// first.

Then, use explode to split the domain in different elements. For the special case where it could start with www, check the value of the first item in the exploded array. If the first one is www, then the second one must be the subdomain.

$url = 'http://www.sub.yourwebsite.com';
$parsed = parse_url($url);
$domain = explode('.', $parsed['host']);
$subdomain = '';

if ($domain[0] == 'www')
    $subdomain = $domain[1];
else
    $subdomain = $domain[0];
Aamir
  • 5.4k
  • 2
  • 31
  • 47