PHP从子域获取域名

2022-01-04 00:00:00 php dns subdomain

我需要编写一个函数来解析包含域名的变量.我最好用一个例子来解释这一点,变量可以包含以下任何内容:

I need to write a function to parse variables which contain domain names. It's best I explain this with an example, the variable could contain any of these things:

here.example.com
example.com
example.org
here.example.org

但是当通过我的函数时,所有这些都必须返回 example.com 或 example.co.uk,基本上是根域名.我确定我以前这样做过,但我已经在谷歌上搜索了大约 20 分钟,但找不到任何东西.任何帮助将不胜感激.

But when passed through my function all of these must return either example.com or example.co.uk, the root domain name basically. I'm sure I've done this before but I've been searching Google for about 20 minutes and can't find anything. Any help would be appreciated.

忽略 .co.uk,假设通过此功能的所有域都有 3 个字母的 TLD.

Ignore the .co.uk, presume that all domains going through this function have a 3 letter TLD.

推荐答案

Stackoverflow 问题存档:

  • 如何从 url 获取域名?
  • 检查域是否等于值?
  • 如何获取基本网址?
  • print get_domain("http://somedomain.co.uk"); // outputs 'somedomain.co.uk'
    
    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;
    }
    

相关文章