从完整 URL 获取域名

新手上路,请多包涵

假设有人输入这样的 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

原文由 ramo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 613
2 个回答

检查下面的代码,它应该可以正常工作。

 <?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'

?>

原文由 stanev01 发布,翻译遵循 CC BY-SA 3.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);

原文由 Basant Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题