36

我有一个可以是以下任何格式的 URL:

http://example.com
https://example.com
http://example.com/foo
http://example.com/foo/bar
www.example.com
example.com
foo.example.com
www.foo.example.com
foo.bar.example.com
http://foo.bar.example.com/foo/bar
example.net/foo/bar

本质上,我需要能够匹配任何正常的 URL。如何example.com 通过单个正则表达式从所有这些中提取(或 .net,无论 tld 是什么。我需要它来处理任何 TLD。)?

4

18 回答 18

49

那么你可以parse_url用来获取主机:

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

然后,您可以做一些花哨的事情来只获得 TLD 和主机

$host_names = explode(".", $host);
$bottom_host_name = $host_names[count($host_names)-2] . "." . $host_names[count($host_names)-1];

不是很优雅,但应该可以。


如果你想要一个解释,这里是:

首先,我们http://通过使用 ' 的功能来获取方案( 等)之间的所有内容parse_url......好吧......解析 URL。:)

然后我们获取主机名,并根据句点所在的位置将其分成一个数组,因此test.world.hello.myname将变为:

array("test", "world", "hello", "myname");

之后,我们取数组 (4) 中的元素数量。

然后,我们从中减去 2 以获得倒数第二个字符串(主机名,或者example,在您的示例中)

然后,我们从中减去 1 得到最后一个字符串(因为数组键从 0 开始),也称为 TLD

然后我们将这两个部分与句点结合起来,您就有了您的基本主机名。

于 2010-04-21T00:38:48.717 回答
17

我在https://gist.github.com/pocesar/5366899中的解决方案

测试在这里http://codepad.viper-7.com/GAh1tP

它适用于任何 TLD 和可怕的子域模式(最多 3 个子域)。

许多域名都包含一个测试。

不会在此处粘贴函数,因为 StackOverflow 中代码的缩进很奇怪(可能有像 github 这样的围栏代码块)

于 2013-04-11T20:30:57.967 回答
15

如果不使用 TLD 列表进行比较,则无法获取域名,因为它们存在许多具有完全相同结构和长度的案例:

  1. www.db.de(子域)与 bbc.co.uk(域)
  2. big.uk.com (SLD) 与 www.uk.com (TLD)

Mozilla 的公共后缀列表应该是最佳选择,因为它被所有主要浏览器使用:
https ://publicsuffix.org/list/public_suffix_list.dat

随意使用我的功能:

function tld_list($cache_dir=null) {
    // we use "/tmp" if $cache_dir is not set
    $cache_dir = isset($cache_dir) ? $cache_dir : sys_get_temp_dir();
    $lock_dir = $cache_dir . '/public_suffix_list_lock/';
    $list_dir = $cache_dir . '/public_suffix_list/';
    // refresh list all 30 days
    if (file_exists($list_dir) && @filemtime($list_dir) + 2592000 > time()) {
        return $list_dir;
    }
    // use exclusive lock to avoid race conditions
    if (!file_exists($lock_dir) && @mkdir($lock_dir)) {
        // read from source
        $list = @fopen('https://publicsuffix.org/list/public_suffix_list.dat', 'r');
        if ($list) {
            // the list is older than 30 days so delete everything first
            if (file_exists($list_dir)) {
                foreach (glob($list_dir . '*') as $filename) {
                    unlink($filename);
                }
                rmdir($list_dir);
            }
            // now set list directory with new timestamp
            mkdir($list_dir);
            // read line-by-line to avoid high memory usage
            while ($line = fgets($list)) {
                // skip comments and empty lines
                if ($line[0] == '/' || !$line) {
                    continue;
                }
                // remove wildcard
                if ($line[0] . $line[1] == '*.') {
                    $line = substr($line, 2);
                }
                // remove exclamation mark
                if ($line[0] == '!') {
                    $line = substr($line, 1);
                }
                // reverse TLD and remove linebreak
                $line = implode('.', array_reverse(explode('.', (trim($line)))));
                // we split the TLD list to reduce memory usage
                touch($list_dir . $line);
            }
            fclose($list);
        }
        @rmdir($lock_dir);
    }
    // repair locks (should never happen)
    if (file_exists($lock_dir) && mt_rand(0, 100) == 0 && @filemtime($lock_dir) + 86400 < time()) {
        @rmdir($lock_dir);
    }
    return $list_dir;
}
function get_domain($url=null) {
    // obtain location of public suffix list
    $tld_dir = tld_list();
    // no url = our own host
    $url = isset($url) ? $url : $_SERVER['SERVER_NAME'];
    // add missing scheme      ftp://            http:// ftps://   https://
    $url = !isset($url[5]) || ($url[3] != ':' && $url[4] != ':' && $url[5] != ':') ? 'http://' . $url : $url;
    // remove "/path/file.html", "/:80", etc.
    $url = parse_url($url, PHP_URL_HOST);
    // replace absolute domain name by relative (http://www.dns-sd.org/TrailingDotsInDomainNames.html)
    $url = trim($url, '.');
    // check if TLD exists
    $url = explode('.', $url);
    $parts = array_reverse($url);
    foreach ($parts as $key => $part) {
        $tld = implode('.', $parts);
        if (file_exists($tld_dir . $tld)) {
            return !$key ? '' : implode('.', array_slice($url, $key - 1));
        }
        // remove last part
        array_pop($parts);
    }
    return '';
}

它有什么特别之处:

  • 它接受每一个输入,如 URL、主机名或带或不带方案的域
  • 列表逐行下载以避免高内存使用
  • 它在缓存文件夹中为每个 TLD 创建一个新文件,因此get_domain()只需要检查file_exists()它是否存在,因此它不需要像TLDExtract那样在每个请求中都包含一个巨大的数据库。
  • 该列表将每 30 天自动更新一次

测试:

$urls = array(
    'http://www.example.com',// example.com
    'http://subdomain.example.com',// example.com
    'http://www.example.uk.com',// example.uk.com
    'http://www.example.co.uk',// example.co.uk
    'http://www.example.com.ac',// example.com.ac
    'http://example.com.ac',// example.com.ac
    'http://www.example.accident-prevention.aero',// example.accident-prevention.aero
    'http://www.example.sub.ar',// sub.ar
    'http://www.congresodelalengua3.ar',// congresodelalengua3.ar
    'http://congresodelalengua3.ar',// congresodelalengua3.ar
    'http://www.example.pvt.k12.ma.us',// example.pvt.k12.ma.us
    'http://www.example.lib.wy.us',// example.lib.wy.us
    'com',// empty
    '.com',// empty
    'http://big.uk.com',// big.uk.com
    'uk.com',// empty
    'www.uk.com',// www.uk.com
    '.uk.com',// empty
    'stackoverflow.com',// stackoverflow.com
    '.foobarfoo',// empty
    '',// empty
    false,// empty
    ' ',// empty
    1,// empty
    'a',// empty    
);

带有解释的最新版本(德语): http:
//www.programmierer-forum.de/domainnamen-ermitteln-t244185.htm

于 2012-03-09T10:48:50.323 回答
6
$onlyHostName = implode('.', array_slice(explode('.', parse_url($link, PHP_URL_HOST)), -2));

用作https://subdomain.domain.com/some/path示例

parse_url($link, PHP_URL_HOST)返回subdomain.domain.com

explode('.', parse_url($link, PHP_URL_HOST))然后subdomain.domain.com分成一个数组:

array(3) {
  [0]=>
  string(5) "subdomain"
  [1]=>
  string(7) "domain"
  [2]=>
  string(3) "com"
}

array_slice然后对数组进行切片,因此只有最后 2 个值在数组中(由 表示-2):

array(2) {
  [0]=>
  string(6) "domain"
  [1]=>
  string(3) "com"
}

implode然后将这两个数组值组合在一起,最终给你结果domain.com

注意:这仅在您期望的最终域中只有一个时才有效.,例如something.domain.comelse.something.domain.net

它不适用于something.domain.co.uk您期望的地方domain.co.uk

于 2013-02-27T15:36:43.017 回答
6

我认为处理这个问题的最好方法是:

$second_level_domains_regex = '/\.asn\.au$|\.com\.au$|\.net\.au$|\.id\.au$|\.org\.au$|\.edu\.au$|\.gov\.au$|\.csiro\.au$|\.act\.au$|\.nsw\.au$|\.nt\.au$|\.qld\.au$|\.sa\.au$|\.tas\.au$|\.vic\.au$|\.wa\.au$|\.co\.at$|\.or\.at$|\.priv\.at$|\.ac\.at$|\.avocat\.fr$|\.aeroport\.fr$|\.veterinaire\.fr$|\.co\.hu$|\.film\.hu$|\.lakas\.hu$|\.ingatlan\.hu$|\.sport\.hu$|\.hotel\.hu$|\.ac\.nz$|\.co\.nz$|\.geek\.nz$|\.gen\.nz$|\.kiwi\.nz$|\.maori\.nz$|\.net\.nz$|\.org\.nz$|\.school\.nz$|\.cri\.nz$|\.govt\.nz$|\.health\.nz$|\.iwi\.nz$|\.mil\.nz$|\.parliament\.nz$|\.ac\.za$|\.gov\.za$|\.law\.za$|\.mil\.za$|\.nom\.za$|\.school\.za$|\.net\.za$|\.co\.uk$|\.org\.uk$|\.me\.uk$|\.ltd\.uk$|\.plc\.uk$|\.net\.uk$|\.sch\.uk$|\.ac\.uk$|\.gov\.uk$|\.mod\.uk$|\.mil\.uk$|\.nhs\.uk$|\.police\.uk$/';
$domain = $_SERVER['HTTP_HOST'];
$domain = explode('.', $domain);
$domain = array_reverse($domain);
if (preg_match($second_level_domains_regex, $_SERVER['HTTP_HOST']) {
    $domain = "$domain[2].$domain[1].$domain[0]";
} else {
    $domain = "$domain[1].$domain[0]";
}
于 2013-04-20T05:39:28.270 回答
6
echo getDomainOnly("http://example.com/foo/bar");

function getDomainOnly($host){
    $host = strtolower(trim($host));
    $host = ltrim(str_replace("http://","",str_replace("https://","",$host)),"www.");
    $count = substr_count($host, '.');
    if($count === 2){
        if(strlen(explode('.', $host)[1]) > 3) $host = explode('.', $host, 2)[1];
    } else if($count > 2){
        $host = getDomainOnly(explode('.', $host, 2)[1]);
    }
    $host = explode('/',$host);
    return $host[0];
}
于 2019-05-03T08:19:34.633 回答
6

我建议使用TLDExtract库进行所有带有域名的操作。

于 2016-04-12T14:40:05.677 回答
4

从主机中提取子域有两种方法:

  1. 第一种更准确的方法是使用 tlds 数据库(如public_suffix_list.dat)并将域与之匹配。在某些情况下,这有点重。有一些 PHP 类可以使用它,例如php-domain-parserTLDExtract

  2. 第二种方法不如第一种准确,但速度很快,而且在很多情况下都能给出正确答案,我为此编写了这个函数:

    function get_domaininfo($url) {
        // regex can be replaced with parse_url
        preg_match("/^(https|http|ftp):\/\/(.*?)\//", "$url/" , $matches);
        $parts = explode(".", $matches[2]);
        $tld = array_pop($parts);
        $host = array_pop($parts);
        if ( strlen($tld) == 2 && strlen($host) <= 3 ) {
            $tld = "$host.$tld";
            $host = array_pop($parts);
        }
    
        return array(
            'protocol' => $matches[1],
            'subdomain' => implode(".", $parts),
            'domain' => "$host.$tld",
            'host'=>$host,'tld'=>$tld
        );
    }
    

    例子:

    print_r(get_domaininfo('http://mysubdomain.domain.co.uk/index.php'));
    

    回报:

    Array
    (
        [protocol] => https
        [subdomain] => mysubdomain
        [domain] => domain.co.uk
        [host] => domain
        [tld] => co.uk
    )
    
于 2016-09-03T13:44:51.290 回答
3

这是我编写的一个函数,用于在没有子域的情况下获取域,无论该域是使用 ccTLD 还是新样式的长 TLD 等...没有查找或已知 TLD 的大量数组,也没有正则表达式. 使用三元运算符和嵌套可以缩短很多时间,但为了便于阅读,我对其进行了扩展。

// Per Wikipedia: "All ASCII ccTLD identifiers are two letters long, 
// and all two-letter top-level domains are ccTLDs."

function topDomainFromURL($url) {
  $url_parts = parse_url($url);
  $domain_parts = explode('.', $url_parts['host']);
  if (strlen(end($domain_parts)) == 2 ) { 
    // ccTLD here, get last three parts
    $top_domain_parts = array_slice($domain_parts, -3);
  } else {
    $top_domain_parts = array_slice($domain_parts, -2);
  }
  $top_domain = implode('.', $top_domain_parts);
  return $top_domain;
}
于 2015-12-15T04:53:28.367 回答
2
function getDomain($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;
}

echo getDomain("http://example.com"); // outputs 'example.com'
echo getDomain("http://www.example.com"); // outputs 'example.com'
echo getDomain("http://mail.example.co.uk"); // outputs 'example.co.uk'
于 2021-05-06T10:29:01.273 回答
2

我对 pocesar 提供的解决方案有疑问。例如,当我使用 subdomain.domain.nl 时,它不会返回 domain.nl。相反,它会返回 subdomain.domain.nl 另一个问题是 domain.com.br 会返回 com.br

我不确定,但我用以下代码解决了这些问题(我希望它会帮助某人,如果是这样的话,我是一个快乐的人):

function get_domain($domain, $debug = false){
    $original = $domain = strtolower($domain);
    if (filter_var($domain, FILTER_VALIDATE_IP)) {
        return $domain;
    }
    $debug ? print('<strong style="color:green">&raquo;</strong> Parsing: '.$original) : false;
    $arr = array_slice(array_filter(explode('.', $domain, 4), function($value){
        return $value !== 'www';
    }), 0); //rebuild array indexes
    if (count($arr) > 2){
        $count = count($arr);
        $_sub = explode('.', $count === 4 ? $arr[3] : $arr[2]);
        $debug ? print(" (parts count: {$count})") : false;
        if (count($_sub) === 2){ // two level TLD
            $removed = array_shift($arr);
            if ($count === 4){ // got a subdomain acting as a domain
                $removed = array_shift($arr);
            }
            $debug ? print("<br>\n" . '[*] Two level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
        }elseif (count($_sub) === 1){ // one level TLD
            $removed = array_shift($arr); //remove the subdomain
            if (strlen($arr[0]) === 2 && $count === 3){ // TLD domain must be 2 letters
                array_unshift($arr, $removed);
            }elseif(strlen($arr[0]) === 3 && $count === 3){
                array_unshift($arr, $removed);
            }else{
                // non country TLD according to IANA
                $tlds = array(
                    'aero',
                    'arpa',
                    'asia',
                    'biz',
                    'cat',
                    'com',
                    'coop',
                    'edu',
                    'gov',
                    'info',
                    'jobs',
                    'mil',
                    'mobi',
                    'museum',
                    'name',
                    'net',
                    'org',
                    'post',
                    'pro',
                    'tel',
                    'travel',
                    'xxx',
                );
                if (count($arr) > 2 && in_array($_sub[0], $tlds) !== false){ //special TLD don't have a country
                    array_shift($arr);
                }
            }
            $debug ? print("<br>\n" .'[*] One level TLD: <strong>'.join('.', $_sub).'</strong> ') : false;
        }else{ // more than 3 levels, something is wrong
            for ($i = count($_sub); $i > 1; $i--){
                $removed = array_shift($arr);
            }
            $debug ? print("<br>\n" . '[*] Three level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
        }
    }elseif (count($arr) === 2){
        $arr0 = array_shift($arr);
        if (strpos(join('.', $arr), '.') === false && in_array($arr[0], array('localhost','test','invalid')) === false){ // not a reserved domain
            $debug ? print("<br>\n" .'Seems invalid domain: <strong>'.join('.', $arr).'</strong> re-adding: <strong>'.$arr0.'</strong> ') : false;
            // seems invalid domain, restore it
            array_unshift($arr, $arr0);
        }
    }
    $debug ? print("<br>\n".'<strong style="color:gray">&laquo;</strong> Done parsing: <span style="color:red">' . $original . '</span> as <span style="color:blue">'. join('.', $arr) ."</span><br>\n") : false;
    return join('.', $arr);
}
于 2016-06-17T14:50:10.547 回答
2

这是适用于所有域的一个,包括具有二级域(如“co.uk”)的域

function strip_subdomains($url){

    # credits to gavingmiller for maintaining this list
    $second_level_domains = file_get_contents("https://raw.githubusercontent.com/gavingmiller/second-level-domains/master/SLDs.csv");

    # presume sld first ...
    $possible_sld = implode('.', array_slice(explode('.', $url), -2));

    # and then verify it
    if (strpos($second_level_domains, $possible_sld)){
        return  implode('.', array_slice(explode('.', $url), -3));
    } else {
        return  implode('.', array_slice(explode('.', $url), -2));
    }
}

看起来这里有一个重复的问题:delete-subdomain-from-url-string-if-subdomain-is-found

于 2017-01-04T11:24:08.310 回答
1

很晚了,我看到你将正则表达式标记为关键字,我的函数就像一个魅力,到目前为止我还没有找到一个失败的 url:

function get_domain_regex($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'];
  }else{
    return false;
  }
}

如果你想要一个没有正则表达式的我有这个,我相信我也从这篇文章中拿走了

function get_domain($url){
  $parseUrl = parse_url($url);
  $host = $parseUrl['host'];
  $host_array = explode(".", $host);
  $domain = $host_array[count($host_array)-2] . "." . $host_array[count($host_array)-1];
  return $domain;
}

它们都工作得很好,但是,我花了一段时间才意识到如果 url 不以 http:// 或 https:// 开头,它将失败,因此请确保 url 字符串以协议开头。

于 2020-01-29T17:45:30.653 回答
0

即使您解析没有 http:// 或 https:// 的 url,此函数也将返回不带任何 url 扩展名的域名

您可以扩展此代码

(?:\.co)?(?:\.com)?(?:\.gov)?(?:\.net)?(?:\.org)?(?:\.id)?

如果您想处理更多二级域名,请使用更多扩展名。

    function get_domain_name($url){
      $pieces = parse_url($url);
      $domain = isset($pieces['host']) ? $pieces['host'] : $url;
      $domain = strtolower($domain);
      $domain = preg_replace('/.international$/', '.com', $domain);
      if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,90}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
          if (preg_match('/(.*?)((?:\.co)?(?:\.com)?(?:\.gov)?(?:\.net)?(?:\.org)?(?:\.id)?(?:\.asn)?.[a-z]{2,6})$/i', $regs['domain'], $matches)) {
              return $matches[1];
          }else  return $regs['domain'];
      }else{
        return $url;
      }
    }
于 2020-09-28T06:37:42.810 回答
0

试试这个:

   preg_match('/(www.)?([^.]+\.[^.]+)$/', $yourHost, $matches);

   echo "domain name is: {$matches[0]}\n"; 

这适用于大多数域。

于 2018-11-03T12:02:25.920 回答
0

我正在使用它来实现相同的目标,并且它始终有效,我希望它对其他人有所帮助。

$url          = https://use.fontawesome.com/releases/v5.11.2/css/all.css?ver=2.7.5
$handle       = pathinfo( parse_url( $url )['host'] )['filename'];
$final_handle = substr( $handle , strpos( $handle , '.' ) + 1 );

print_r($final_handle); // fontawesome 
于 2021-01-27T20:45:27.887 回答
0

最简单的解决方案

@preg_replace('#\/(.)*#', '', @preg_replace('#^https?://(www.)?#', '', $url))
于 2021-03-10T06:55:20.313 回答
-1

试试这个:

<?php
  $host = $_SERVER['HTTP_HOST'];
  preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
  echo "domain name is: {$matches[0]}\n";
?>
于 2017-01-11T20:43:58.790 回答