PHP 函数获取 URL 的子域

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5292937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:53:23  来源:igfitidea点击:

PHP function to get the subdomain of a URL

phpsubdomain

提问by Damiano

Is there a function in PHP to get the name of the subdomain?

PHP中是否有获取子域名称的函数?

In the following example I would like to get the "en" part of the URL:

在以下示例中,我想获取 URL 的“en”部分:

en.example.com

回答by Michael Deal

Here's a one line solution:

这是一个单行解决方案:

array_shift((explode('.', $_SERVER['HTTP_HOST'])));

Or using your example:

或使用您的示例:

array_shift((explode('.', 'en.example.com')));

EDIT: Fixed "only variables should be passed by reference" by adding double parenthesis.

编辑:通过添加双括号修复“仅变量应通过引用传递”。


EDIT 2: Starting from PHP 5.4you can simply do:


编辑 2:从PHP 5.4开始,您可以简单地执行以下操作:

explode('.', 'en.example.com')[0];

回答by Mike Lewis

Uses the parse_urlfunction.

使用parse_url函数。

$url = 'http://en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomain = $host[0];
echo $subdomain;

For multiple subdomains

对于多个子域

$url = 'http://usa.en.example.com';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomains = array_slice($host, 0, count($host) - 2 );
print_r($subdomains);

回答by mazon

You can do this by first getting the domain name (e.g. sub.example.com => example.co.uk) and then use strstr to get the subdomains.

您可以通过首先获取域名(例如 sub.example.com => example.co.uk)然后使用 strstr 获取子域来完成此操作。

$testArray = array(
    'sub1.sub2.example.co.uk',
    'sub1.example.com',
    'example.com',
    'sub1.sub2.sub3.example.co.uk',
    'sub1.sub2.sub3.example.com',
    'sub1.sub2.example.com'
);

foreach($testArray as $k => $v)
{
    echo $k." => ".extract_subdomains($v)."\n";
}

function extract_domain($domain)
{
    if(preg_match("/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i", $domain, $matches))
    {
        return $matches['domain'];
    } else {
        return $domain;
    }
}

function extract_subdomains($domain)
{
    $subdomains = $domain;
    $domain = extract_domain($subdomains);

    $subdomains = rtrim(strstr($subdomains, $domain, true), '.');

    return $subdomains;
}

Outputs:

输出:

0 => sub1.sub2
1 => sub1
2 =>
3 => sub1.sub2.sub3
4 => sub1.sub2.sub3
5 => sub1.sub2

回答by JMW

http://php.net/parse_url

http://php.net/parse_url

<?php
  $url = 'http://user:[email protected]/path?argument=value#anchor';
  $array=parse_url($url);
  $array['host']=explode('.', $array['host']);

  echo $array['host'][0]; // returns 'en'
?>

回答by Sascha Frinken

As the only reliable source for domain suffixes are the domain registrars, you can't find the subdomain without their knowledge. There is a list with all domain suffixes at https://publicsuffix.org. This site also links to a PHP library: https://github.com/jeremykendall/php-domain-parser.

由于域后缀的唯一可靠来源是域注册商,因此您无法在他们不知情的情况下找到子域。https://publicsuffix.org 上有一个包含所有域后缀的列表。该站点还链接到一个 PHP 库:https: //github.com/jeremykendall/php-domain-parser

Please find an example below. I also added the sample for en.test.co.uk which is a domain with a multi suffix (co.uk).

请在下面找到一个例子。我还添加了 en.test.co.uk 的示例,这是一个带有多后缀 (co.uk) 的域。

<?php

require_once 'vendor/autoload.php';

$pslManager = new Pdp\PublicSuffixListManager();
$parser = new Pdp\Parser($pslManager->getList());
$host = 'http://en.example.com';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;


$host = 'http://en.test.co.uk';
$url = $parser->parseUrl($host);

echo $url->host->subdomain;

回答by Arjen

Simplest and fastest solution.

最简单和最快的解决方案。

$sSubDomain = str_replace('.example.com','',$_SERVER['HTTP_HOST']);

回答by Kamafeather

Simply...

简单地...

    preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $url, $match);

Just read $match[1]

只需阅读$match[1]

Working example

工作示例

It works perfectly with this list of urls

它与此网址列表完美配合

$url = array(
    'http://www.domain.com', // www
    'http://domain.com', // --nothing--
    'https://domain.com', // --nothing--
    'www.domain.com', // www
    'domain.com', // --nothing--
    'www.domain.com/some/path', // www
    'http://sub.domain.com/domain.com', // sub
    'опубликованному.значения.ua', // опубликованному ;)
    'значения.ua', // --nothing--
    'http://sub-domain.domain.net/domain.net', // sub-domain
    'sub-domain.third-Level_DomaIN.domain.uk.co/domain.net' // sub-domain
);

foreach ($url as $u) {
    preg_match('/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/i', $u, $match);
    var_dump($match);
}

回答by Jared Farrish

$REFERRER = $_SERVER['HTTP_REFERER']; // Or other method to get a URL for decomposition

$domain = substr($REFERRER, strpos($REFERRER, '://')+3);
$domain = substr($domain, 0, strpos($domain, '/'));
// This line will return 'en' of 'en.example.com'
$subdomain = substr($domain, 0, strpos($domain, '.')); 

回答by Jeacovy Gayle

PHP 7.0: Using the explode function and create a list of all the results.

PHP 7.0:使用爆炸函数并创建所有结果的列表。

list($subdomain,$host) = explode('.', $_SERVER["SERVER_NAME"]);

Example: sub.domain.com

示例:sub.domain.com

echo $subdomain; 

Result: sub

结果:子

echo $host;

Result: domain

结果:域

回答by Jeacovy Gayle

$domain = 'sub.dev.example.com';
$tmp = explode('.', $domain); // split into parts
$subdomain = current($tmp);
print($subdomain);     // prints "sub"

As seen in a previous question: How to get the first subdomain with PHP?

如上一个问题所示: How to get the first subdomain with PHP?