2

我正在尝试从用户输入的 URL 字符串中获取域名和 TLD(无子域),该字符串可能有也可能没有协议、目录、子域、文件名等。

换句话说,给定以下任何一项:

example.com
www.example.com
sub.example.com
example.com/whatever/hey.html
http://example.com
https://subdomain.example.com
ftp://example.com/whatever/hey.html

我应该总是以:example.com.

现在这就是我正在做的事情:

$hostParts = explode('.', parse_url($URL, PHP_URL_HOST));
$tld = array_pop($hostParts);
$domain = array_pop($hostParts);
$domain = $domain . "." . $tld;

但是,如果提供的 URL 没有协议,它就会中断。为什么parse_url在这种情况下无法获得主机?

4

1 回答 1

3

根据定义,URL 包含协议或方案。检查 // 如果不存在,则将 // 添加到字符串。这在 PHP < 5.4.7 中可能有所不同,因此如果没有协议,可以添加 http://。

于 2013-10-25T19:42:15.520 回答