为什么parse_url返回null?

时间:2018-10-30 18:18:49

标签: php

我知道这是一个简单的问题。但我似乎无法真正理解为什么此函数返回null。我正在尝试只是url主机,并且它返回null。在下面的示例中,我通过了google.com。我试图返回一个仅显示“ google”的数组

当我传递http://www.google.com时,也只是“ www.google.com”

下面是我的代码

    $test = parse_url("google.com",PHP_URL_HOST);


    var_dump($test);

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

parse_url通常返回一个组件数组。如果无法确定组件之一,则将其设置为null。第二个参数将允许您获取特定的组件,而不必将其从数组中拉出。

通过传入PHP_URL_HOST,您请求的是parse_url数组的host部分。它返回null,因为google.com不是有效的URL,因此它不能确定主机。缺少协议(对于google.com,https://)。

如果您通过https://www.google.com,则它将返回www.google.com,因为这是主机域。如果要始终获得google而不管协议和子域如何,那么除了通过parse_url传递它之外,您还需要做更多的事情,因为没有任何组件可以满足您的要求。< / p>

您将按照此问题的要求来寻找一些东西: Getting domain name without TLD

答案 1 :(得分:-2)

function getHost($Address) { 
   $parseUrl = parse_url(trim($Address)); 
   return trim($parseUrl['host'] ? $parseUrl['host'] : array_shift(explode('/', $parseUrl['path'], 2))); 
} 

getHost("example.com"); // Gives example.com 
getHost("http://example.com"); // Gives example.com 
getHost("www.example.com"); // Gives www.example.com 
getHost("http://example.com/xyz"); // Gives example.com