2015-05-29 91 views
5

我怎么能只返回一个域名URL的分割PHP字符串

例如的TLD,如果我有以下几点:

www.domain.co.uk我想回到刚才的.co.uk

和同为domain.co.uk

与同为其他TLDs(.com, .co, .org etc)

是否有一个简单的方法来做到这一点在PHP中不使用Regex

我想用explode的,但即时不太熟悉

+0

检查php parse_url –

+1

它不会帮助。 @MangeshSatheIND – Viral

+0

parse_url会给你域名,然后对其进行正则表达式,你可以得到预期的.com/.co.uk等。 –

回答

2

您可以使用库调用tldextract.php

在此查找https://github.com/data-ac-uk/equipment/blob/master/_misc/tldextract.php

用法很简单:

$extract = new TLDExtract(); 
$components = $extract('http://forums.bbc.co.uk/'); 
echo $components['tld']; // co.uk 

现在多么简单的事?

如果您阅读了代码,可以看到它在fetchTldList()函数中使用了tlds的大list

+0

虽然这个答案(在后台)正在利用正则表达式,提供的资源(publicsuffix.org)非常有帮助! +1 – ohaal

+0

谢谢@ohaal :) –

0

此功能适用于www和非www域名。不适用于子域名。为了获得更好的结果,您需要使用正则表达式或库。

$domain = "www.domain.co.uk"; 
    function tld($domain) 
    { 
     if (strstr('www', $domain)) { 
      $part = 3; 
     } else { 
      $part = 2; 
     } 
     $expld = explode('.', $domain); 
     if (count($expld) > $part) { 
      return $expld[count($expld) - 2] . '.' . $expld[count($expld) - 1]; 
     } else { 
      return $expld[count($expld) - 1]; 
     } 
    } 
1
$returnHostName = parse_url($url, PHP_URL_HOST) //it will retrun 'domain' in your case 
$returnArrayType = explode($returnHostName, $returnHostName); //explode it from string 'domain' 

现在没事了可变returnArrayType包含您所需的输出,但在阵列的形式,你可以从调用它的指数得到它。

检查它是否会工作。

1

不是正则表达式,不是parse_url()不会帮助你。

您需要使用Public Suffix List来提取TLD的库,我推荐使用TLDExtract