开发者

How to find subdomain from a url

开发者 https://www.devze.com 2023-02-08 01:42 出处:网络
URL = http://company.website.com/pages/users/add/ How do i find the subdomain from this via PHP Such that $subdomain = \'company\'开发者_运维问答

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


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.


Or to avoid the regex:

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

精彩评论

暂无评论...
验证码 换一张
取 消