Dhruv Kumar Jha
Dhruv Kumar Jha

Reputation: 6567

How to find subdomain from a url

URL = http://company.website.com/pages/users/add/

How do i find the subdomain from this via PHP

Such that $subdomain = 'company'

And $url = '/pages/users/add/'

Upvotes: 0

Views: 1631

Answers (2)

dustinl4m3
dustinl4m3

Reputation: 159

Or to avoid the regex:

$sections = explode('.', $url_parsed["host"]);
$subdomain = $sections[0];

Upvotes: 1

Justin Johnson
Justin Johnson

Reputation: 31300

You'll want to take a look at PHP's parse_url. This will give you the basic components of the URL which will make it easier to parse out the rest of your requirements (the subdomain)

$url        = 'http://company.website.com/pages/users/add/';
$url_parsed = parse_url($url);
$path       = $url_parsed['path']; // "pages/users/add/"

And then a simple regex* to parse $url_parsed['host'] for subdomains:

$subdomain = preg_match("/(?:(.+)\.)?[^\.]+\.[^\.]+/i", $url_parsed['host'); 
// yields array("company.website.com", "company")

* I tested the regex in JavaScript, so you may need to tweak it a little.

Upvotes: 5

Related Questions