How to find subdomain from a url

孤者浪人 提交于 2021-01-29 20:15:47

问题


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


回答1:


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.




回答2:


Or to avoid the regex:

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


来源:https://stackoverflow.com/questions/4883687/how-to-find-subdomain-from-a-url

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