如何使用php获取URL主机 [英] how to get URL host using php

查看:36
本文介绍了如何使用php获取URL主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取任何网址的主机名,例如,如果我有以下网址

I would like to get the host name of any url for example if i've the following url

$url = "http://www.google.com";

然后我只想获取 google. 之后和扩展点 . 之前的内容,以便它可以应用于所有类型网址.

then i want to get only google what is after dot . and before extension dot . so that it can be applied for all types of urls.

所以结果应该是 google !我认为这可能需要正则表达式或以某种方式知道怎么做,谢谢.

so the results should be google ! i think this might needs regex or somehow any idea how to do it , Thanks.

推荐答案

你可以试试

echo __extractName("http://google.com"); 
echo __extractName("http://office1.dept1.google.com");
echo __extractName("http://google.co.uk");


function __extractName($url)
{
  $domain = parse_url($url , PHP_URL_HOST);
  if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $list)) {
    return substr($list['domain'], 0,strpos($list['domain'], "."));
  }
  return false;
}

输出

google
google 
google 

这篇关于如何使用php获取URL主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆