简体   繁体   English

PHP从字符串获取带有子域的域

[英]PHP get domain with subdomain from string

Im using the following function to cut domain from string: 我使用以下功能从字符串中剪切域:

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

I need to cut subdomain + domain how should i change preg_match to get it? 我需要削减子域+域,我应该如何更改preg_match才能获得它?

PS i was searching solution but everyone wants to cut only domain without sub. PS 我正在寻找解决方案,但每个人都想只削减域名而无子。

If you can't work out the regexp, a more procedural approach might be: 如果您无法计算正则表达式,则可以使用更具过程性的方法:

$pieces = parse_url($url);
$aDomains = explode('.', $pieces['host']);
$sub = array_shift($aDomains);
$restofdomain = implode($aDomains);

...if you're always going to just want the first domain (ie it wouldn't work with a root domain like 'somedomain.com'. ...如果您总是只想要第一个域(即,它不适用于“ somedomain.com”之类的根域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM