1

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

I/P:https ://stackoverflow.com/users/login | 运营商:stackoverflow.com

I/P:stackoverflow.com/users/login | 运营商:stackoverflow.com

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

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

4

4 回答 4

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如果未找到域,则为空字符串

于 2015-11-16T10:05:37.213 回答
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');
于 2015-11-16T09:18:43.500 回答
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'))

演示

于 2015-11-16T09:11:40.283 回答
0

您可以使用正则表达式,如本解决方案中所述:获取 URL 的一部分 (Regex)

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

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

于 2015-11-16T09:12:43.320 回答