沃梦达 / 编程问答 / php问题 / 正文

PHP从子域获取域名

PHP Getting Domain Name From Subdomain(PHP从子域获取域名)

本文介绍了PHP从子域获取域名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
    }
    

    这篇关于PHP从子域获取域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP从子域获取域名

基础教程推荐