douliao8318 2013-09-21 16:56
浏览 10

关于查找域名[关闭]

I search in internet and i found this code for find domain name

function get_domain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) 
{
return $regs['domain'];
}
return false;
}

Its works for http://www.google.com or http://www.google.co.uk

But its not working for test.web.tv.

Anybody can help me ?

How i can find min domain ?

Thanks

  • 写回答

1条回答 默认 最新

  • duanbi3151 2013-09-21 17:12
    关注

    The function parse_url() requires a valid URL. In this case test.web.tv isn't valid, so parse_url() won't give you the expected results. In order to get around this, you could first check if the URL has the http:// prefix, and if it doesn't, manually prepend it. That way, you can get around the limitation of parse_url().

    However, I think it'd be better to use the following function.

    function getDomain($url) 
    {    
        if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            $url = "http://" . $url;
        }
    
        $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
        return $domain;
    }
    

    Explanation:

    • The given URL's passed to parse_url() with the PHP_URL_HOST flag and the full host is obtained
    • It's exploded with . as a delimiter
    • The last two pieces of the array is sliced -- ie. the domain name
    • It's joined back using implode()

    Test:

    echo getDomain('test.web.tv');
    

    Output:

    web.tv
    

    Demo!

    Note: It's a modified version of my own answer here combined with Alix's answer here.

    This function currently doesn't work for .co.uk domain extensions -- you can easily add a check and change the array_slice function accordingly.

    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?