从给定 URL 获取主机名

Get Host name from given URL

如何从以下示例中获取主机名。

I/P: https://whosebug.com/users/login | O/P: whosebug.com

I/P: whosebug.com/users/login | O/P: whosebug.com

I/P: /users/login | O/P: (return empty string)

我检查了 parse_url 功能,但没有 return 我需要的功能。因为,我是 PHP 的初学者,这对我来说很难。如果你有什么想法,请回答。

你可以试试这个 -

$url = ' https://whosebug.com/users/login';

function return_host($url)
{
  $url = str_replace(array('http://', 'https://'), '', $url); // remove protocol if present
  $temp = explode('/', $url); // explode the url by /
  if(strpos($temp[0], '.com')) { // check the url part
     return $temp[0];
  }
  else {
     return false;
  }
}

echo return_host($url);

更新

对于其他域类型,只需更改检查 -

if(strpos($temp[0], '.com') || strpos($temp[0], '.org') || strpos($temp[0], '.net'))

DEMO

您可以使用正则表达式,如本解决方案中所述:Getting parts of a URL (Regex)

或者您可以为此使用 PHP 函数:http://php.net/manual/en/function.parse-url.php

我会建议第二种(如果您不确切知道它们的工作原理,RegExes 可能会很棘手)。

你可以试试这个

<?php  

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

echo getHost('http://whosebug.com/users/login');

这应该适用于所有类型的域名

$url = " https://whosebug.com/users/login";
// trailing slash for edge case, it will return empty string for strstr function regardless
$test = str_replace(array("http://", "https://"), "", $url) . "/";
$domain = strstr($test, "/", true);
echo $domain; // whosebug.com
如果找不到域,

$domain 将是一个空字符串