是否有一个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']中。