在可能包含协议的字符串上运行 parse_url()


Running parse_url() on a string that may not contain the protocol

我正在尝试从用户输入的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在这种情况下无法获得主机?

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