Home  >  Article  >  Backend Development  >  PHP实现获取域名的方法小结_PHP

PHP实现获取域名的方法小结_PHP

WBOY
WBOYOriginal
2016-05-31 19:28:211072browse

本文实例总结了PHP实现获取域名的方法。分享给大家供大家参考。具体实现方法如下:

方法一(用 系统变量)   

代码如下:

//缺点不使用传递过来的地址和不支持系统变量的主机   
echo $_SERVER['HTTP_HOST'];

   

方法二(用自带函数)   

代码如下:

$url = 'http://www.bitsCN.com/index.php?referer=bitsCN.com';   
$arr_url = parse_url($url);   
echo $arr_url['host'];

方法三( 自己写函数)   

代码如下:

function getdomain($url)   
{   
  $url = str_replace('http://',”,$url);  //如果有http前缀,则去掉   
  $pos = strpos($url,'/');   
  if($pos === false)   
   {   
      return $url;   
   }else  
   {   
      return substr($url, 0, $pos);   
   }   
}   
echo getdomain($url);

方法四(用正则)   

代码如下:

preg_match("/^(http://)?([^/]+)/i", $url, $arr_domain);   
echo $arr_domain[2];

希望本文所述对大家的PHP程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn