从完整的URL中获取域名

42

假设有人输入了这样的 URL:

http://i.imgur.com/a/b/c?query=value&query2=value

我希望返回: imgur.com

不要返回i.imgur.com

这是我现在拥有的代码

$sourceUrl = parse_url($url);
$sourceUrl = $sourceUrl['host'];

但是这会返回 i.imgur.com


这个方法如何?它可以获取一个域名的真实名称。 - user557846
请参阅:https://dev59.com/0nVC5IYBdhLWcg3wcwwm - user149341
https://dev59.com/U3VC5IYBdhLWcg3wfxM8 - Malfunction
https://gist.github.com/praisedpk/64bdb80d28144aa78d58469324432277 - Hamid Sarfraz
8个回答

83

请检查下面的代码,它应该可以很好地完成工作。

<?php

function get_domain($url)
{
  $pieces = parse_url($url);
  $domain = isset($pieces['host']) ? $pieces['host'] : $pieces['path'];
  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;
}

print get_domain("http://mail.somedomain.co.uk"); // outputs 'somedomain.co.uk'

?>

3
这有点棘手。对于一级国家和地区顶级域名的子域名,例如 blah.blah.de,它将返回不正确的结果。但是如果不使用公共后缀列表,就没有其他办法解决这个问题。 - user149341
这对于 www.domain.com 是行不通的 - parse_url() 需要一个协议 (http://) 来定义主机,否则它只是路径。第一条需要一个次要条件:$domain = ( empty( $domain ) && isset( $pieces['path'] ) ) ? $pieces['path'] : $domain; - Howdy_McGee
@stanev01 这个无法在 https://successonline.services/why-you-should-stay-in-college-even-if-youre-a-future-ceo/ 上运行。 - Bharat Dangar
@BharatDangar 使用 '/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,10})$/i' 作为 preg_replace() 的第一个参数,以允许 TLD 中最多有 10 个字符。 - vbnm

8

您需要使用公共后缀列表的包。是的,您可以在parse_url()周围使用字符串函数或正则表达式,但在复杂的URL中,它们会产生不正确的结果。

我建议使用TLDExtract进行域名解析,以下是示例代码:

$url = 'http://i.imgur.com/a/b/c?query=value&query2=value';

parse_url($url, PHP_URL_HOST); // will return 'i.imgur.com'

$extract = new LayerShifter\TLDExtract\Extract();
$result = $extract->parse($url);
$result->getFullHost(); // will return 'i.imgur.com'
$result->getSubdomain(); // will return 'i'
$result->getRegistrableDomain(); // will return 'imgur.com'
$result->getSuffix(); // will return 'com'

1
它已经过时了,请使用https://github.com/jeremykendall/php-domain-parser。 - user1986815

4
我发现了一个非常有用的库,使用publicsuffix.org,PHP域名解析器是一个基于公共后缀列表实现的PHP域名解析器。

https://github.com/jeremykendall/php-domain-parser

 <?php 
 // this will do the job

 require_once '../vendor/autoload.php';

 $pslManager = new Pdp\PublicSuffixListManager();
 $parser = new Pdp\Parser($pslManager->getList());
 var_dump($parser->getRegistrableDomain('www.scottwills.co.uk'));
 ?>
(16) "scottwills.co.uk"

2
下面的代码应该非常适合这个任务。
function get_domain($url){
  $charge = explode('/', $url);
  $charge = $charge[2]; //assuming that the url starts with http:// or https://
  return $charge;
}

echo get_domain('http://www.example.com/example.php');

0

检查简单代码 您可以获取主机、子域名、域名和扩展名

$urls = array("https://www.face.com","www.asdasd.asd","sasdas.com/asdas","sdfsdf.sdf","https://app.abcdlink.com/user/test/");

功能:

function getDomainname($a)
{
   $r = "(?P<host>(?:(?P<subdomain>[\w\.]+)\.)?" . "(?P<domain>\w+\.(?P<extension>\w+)))";
   $r = "!$r!";// Delimiters
   preg_match($r, $a, $out);

// if you need only domain then return $out['domain'];
// if you need only host then return $out['host'];
// if you need only subdomain then return $out['subdomain'];
// if you need only extension then return $out['extension'];

// Full Data array
    return $out;

}

$urls = array_map('getDomainname', $urls);

或者

function getsingaldomainHost($a)
{
    $a = (substr($a, 0, 7) == "http://" || substr($a, 0, 8) == "https://") ?  $a : 'http://' . $a;
    $r = "/(?P<host>(?:(?P<subdomain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z0-9]{0,62}))?(?P<domain>[a-z0-9][a-z0-9\-]{0,63}\.[a-z0-9]{0,62})(?P<extension>[a-z0-9][a-z0-9\-]{0,63}\.[a-z\.]{0,61}))$/i";
    $pieces = parse_url($a);
    if (isset($pieces['host'])) {
        $domain = substr($pieces['host'], 0, 4) == "www." ?  $pieces['host'] : 'www.' . $pieces['host'];
    } else {
        $domain = $pieces['path'];
    }

    if (preg_match($r, $domain, $regs)) {
        return substr($regs['host'], 0, 4) == "www." ? substr($regs['host'], 4) : $regs['host'];
    } else {
        if ($rr == 1) {
            return false;
        } else {
            return $a;
        }
    }
}
$urls = array_map('getsingaldomainHost', $urls);

-1
     if(substr_count($original_url, 'http://')) {
    if(substr_count($original_url, 'www.')) {
        // url style would be 'http://www.abc.xxx/page?param' or http://www.abc.xxx.xx/page?param
        // extract 'abc'
        $temp = explode('.', $original_url);

        $store_url = $temp[1];
        // now 
        // $temp[2] = xxx or xxx/page?param 
        // $temp[3] = null or xx/page?param 

        //if ($temp[3] == null) { // then we are sure that $temp[2]== "xxx/page?param"
                    if(sizeof($temp) > 3) {
            // extract "xxx" from "xxx/page?param" and append to store url so it will be "abc.xxx"  
            $temp = explode('/',$temp[2]);
            $store_url .= '.'.$temp[0];
        }
        else { 
            // then we are sure that $temp[2]== "xxx" and then $temp[3] == "xx/page?param"
            //                  or   $temp[2]== xxx/page?stripped-link from second dot(.)
            if(substr_count($temp[2], '/')) { // in case  $temp[2]== xxx/page?stripped-link from second dot(.)
                // extract "xxx" from "xxx/page?stripped-link" and appent to store url so it will be "abc.xxx"
                $temp = explode('/',$temp[2]);
                $store_url .= '.'.$temp[0]; // "abc".="xxx" ==> abc.xxx
            }
            else { // in case $temp[2]== "xxx" and then $temp[3] == "xx/page?param"
                $store_url .= '.'.$temp[2]; // "abc".="xxx" ==> abc.xxx
                // extract "xx" from "xx/page?param" and appent to store url so it will be "abc.xxx.xx"
                $temp = explode('/',$temp[3]);
                if(strlen($temp[0])==2) {
                    $store_url .= '.'.$temp[0];
                }
            }
        }
    }
    else {
        // url style would be 'http://abc.xxx/page?param' or 'http://abc.xxx.xx/page?param'
        // remove 'http://'
        $temp = substr($original_url, 7);
        // now temp would be either 'abc.xxx/page?param' or 'abc.xxx.xx/page?param'
        // explode with '/'
        $temp = explode('/', $temp);
        $store_url = $temp[0];
    }
}
else if(substr_count($original_url, 'www.')) {
    // url style would be 'www.abc.xxx/page?param' or 'www.abc.xxx.xx/page?param'
    // remove 'www.'
    $temp = substr($original_url, 4);
    // now, $temp would be either "abc.xxx/page?param" or "abc.xxx.xx/page?param"
    // explode with '/'
    $temp = explode('/', $temp);
    $store_url = $temp[0];
}
else {
    // url style would be 'abc.xxx/page?param' or 'abc.xxx.xx/page?param'
    //explode with '/'
    $temp = explode('/', $original_url);
    $store_url = $temp[0];
}

这是一个用于从URL获取主机名的函数。原始的URL是你的URL,而$store_url返回主机的URL。 - mahipal purohit

-5
如果您只想要域名,请尝试以下操作:
$domain = $_SERVER['SERVER_NAME'];

echo $domain;

-5

使用这个:

$uri = "$_SERVER[REQUEST_URI]";<br>
print($uri);

例子:

http://exemple.com/?directory<br>
Result:
/?diretory

该命令获取目录而非域名。


1
问题涉及用户输入的URL,而不是他们正在访问的地址。 - robmcvey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接