是否有一个PHP函数来检索“第一部分”?URL


Is there a PHP function for retrieving the "first part" of a URL?

是否有一个PHP函数用于检索URL的"第一部分",类似于dirname/basename对文件路径的行为?

类似

的内容
echo "url_basename('example.com/this_post/12312')"

返回

example.com

parse_url应该可靠地做到这一点。

下面是用给定URL输出example.com的代码:

$url = 'example.com/this_post/12312';
if (strpos($url,'http') === FALSE) {
    $url = 'http://'.$url;
}
$arrURLParts = parse_url($url);
$host = $arrURLParts['host'];
echo $host;

警告:如果省略部分以确保URL以http开头,则parse_url将返回空主机并将'example.com/this_post/12312'放入$arrURLParts['path']中。