如何使用PHP从URL获取基本域名? [英] How to get the base domain name from an URL using PHP?
问题描述
我需要从URL获取域名.以下示例均应返回google.com
:
I need to get the domain name from an URL. The following examples should all return google.com
:
google.com
images.google.com
new.images.google.com
www.google.com
类似地,以下URL都应返回google.co.uk
.
Similarly the following URLs should all return google.co.uk
.
google.co.uk
images.google.co.uk
new.images.google.co.uk
http://www.google.co.uk
我不愿意使用正则表达式,因为类似domain.com/google.com
之类的东西可能会返回错误的结果.
I'm hesitant to use Regular Expressions, because something like domain.com/google.com
could return incorrect results.
如何使用PHP获得顶级域名?这需要在所有平台和主机上正常工作.
How can I get the top-level domain, using PHP? This needs to work on all platforms and hosts.
推荐答案
您可以执行以下操作:
$urlData = parse_url($url);
$host = $urlData['host'];
**更新**
我能想到的最好方法是对所有要处理的TLD进行映射,因为某些TLD可能很棘手(co.uk).
The best way I can think of is to have a mapping of all the TLDs that you want to handle, since certain TLDs can be tricky (co.uk).
// you can add more to it if you want
$urlMap = array('com', 'co.uk');
$host = "";
$url = "http://www.google.co.uk";
$urlData = parse_url($url);
$hostData = explode('.', $urlData['host']);
$hostData = array_reverse($hostData);
if(array_search($hostData[1] . '.' . $hostData[0], $urlMap) !== FALSE) {
$host = $hostData[2] . '.' . $hostData[1] . '.' . $hostData[0];
} elseif(array_search($hostData[0], $urlMap) !== FALSE) {
$host = $hostData[1] . '.' . $hostData[0];
}
echo $host;
这篇关于如何使用PHP从URL获取基本域名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!