在php中可以使用内置函数gethostbyname获取域名对应的IP地址,比如:
<?php
echo gethostbyname("www.jb200.com");
?>
以上会输出域名所对应的的IP。
对于做了负载与cdn的域名来讲,可能返回的结果会有不同,这点注意下。
下面来说说获取域名的方法,例如有一段网址:http://www.jb200.com/all-the-resources-of-this-blog.html
方法1,
本地测试则会输出localhost。
方法2,使用parse_url函数;
<?php $url ="http://www.jb200.com/index.php?referer=jb200.com"; $arr=parse_url($url); echo "<pre>"; print_r($arr); echo "</pre>"; ?>
输出为数组,结果为:
说明:
scheme对应着协议,host则对应着域名,path对应着执行文件的路径,query则对应着相关的参数;
方法3,采用自定义函数。
<?php
$url ="http://www.jb200.com/index.php?referer=jb200.com";
get_host($url);
function get_host($url){
//首先替换掉http://
$url=Str_replace("http://","",$url);
//获得去掉http://url的/最先出现的位置
$position=strpos($url,"/");
//如果没有斜杠则表明url里面没有参数,直接返回url,
//否则截取字符串
if($position==false){
echo $url;
}else{
echo substr($url,0,$position);
}
}
?>
方法4,使用php正则表达式。
<?php
header("Content-type:text/html;charset=utf-8");
$url ="http://www.jb200.com/index.php?referer=jb200.com";
$pattern="/(http://)?(.*)//";
if(preg_match($pattern,$url,$arr)){
echo "匹配成功!";
echo "匹配结果:".$arr[2];
}
?>
您可能感兴趣的文章: