从给定的URL获取主机名

时间:2015-11-16 08:51:02

标签: php url html-parsing url-parsing urlparse

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

  

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

     

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

     

I / P:/ users / login | O / P :(返回空字符串)

我检查了parse_url函数,但没有返回我需要的内容。因为,我是PHP的初学者,对我来说很难。如果您有任何想法,请回答。

4 个答案:

答案 0 :(得分:2)

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

$url = " https://stackoverflow.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; // stackoverflow.com
如果找不到域名,

$domain将为空字符串

答案 1 :(得分:1)

你可以试试这个 -

$url = ' https://stackoverflow.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

答案 2 :(得分:1)

你可以试试这个

<?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://stackoverflow.com/users/login');

答案 3 :(得分:0)

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

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

我会建议第二个(如果你不确切知道它们是如何工作的,那么RegEx可能会很棘手)。

相关问题