2012-02-07 43 views
2

您的需要返回爲實際的域名和擴展,分別如何將域名拆分爲sld和tld(擴展名)?

http://www.something.com 

應該返回:sld = somethingtld= com

something.co.uk 

應該返回:sld = somethingtld= co.uk

我對正則表達式不太熟悉,所以我真的需要一些幫助來處理這個問題。

我想我可以使用parse_url(),並檢查host,但那又如何?

+0

http://gimme-teh-codez.com – 2012-02-07 11:52:23

+0

在第二個例子中'co'是SLD,'uk'是TLD。 – Quentin 2012-02-07 11:57:43

+0

這可能會幫助你, http://stackoverflow.com/questions/1201194/php-getting-domain-name-from-subdomain – 2012-02-07 11:59:52

回答

4

正如您所說,您可以使用$urlCompontents=parseUrl($url)來獲取主機名。然後,您可以使用explode(".",$urlCompontents["host"])將主機名拆分爲不同的部分,例如。 array("example","co","uk")。您必須通過將部件與列表進行比較來完成剩下的工作,因爲沒有固定的規則,即e.G. 「英國」本身不被認爲是頂級域名,但「co.uk」是。但是你不需要任何正則表達式。

0

拆分字符串.字符(不需要正則表達式),然後從結尾處理結果數組。

由於沒有簡單的模式可以準確描述它們,因此您需要手動保留將SLD直接銷售給最終用戶的索引。請注意,可能有influx of new TLDs

0

下面的代碼將在'。'上拆分(爆炸)主機字符串。字符。需要一個簡單的tld的異常數組,並且我已經將co.uk放入其中。只有這些例外,它將使用主機名的最後兩個塊。

$h='something.co.uk'; 
$x=array('uk'=>'co'); // exceptions of tld's with 2 parts 
$r=explode('.',$h); // split host on dot 
$t=array_pop($r); // create tld 
if(isset($x[$t]) and end($r)==$x[$t]) $t=array_pop($r).'.'.$t; // add to tld for the exceptions 
$d=implode('.',$r); // domain 
echo "sld:$d, tld:$t"; 

結果是SLD:什麼東西,TLD:co.uk

2

這裏是我使用。希望能幫助到你。

function extractTLD($domain) 
{ 
    $productTLD = ''; 
    $tempstr = explode(".", $domain); 
    unset($tempstr[0]); 
    foreach($tempstr as $value){ 
     $productTLD = $productTLD.".".$value; 
    }  
    return $productTLD; 
} 
+0

這是寫得很糟糕,通過刪除您始終期望www的域的第一部分。或其他子域名,這不適合domain.com格式 – 2014-05-02 13:20:34

0
$pos = strpos('domain.com', '.'); 
$length= strlen('domain.com'); 
$domain = substr('domain.com', 0, $pos); 
$tld= substr('domain.com', $pos, $length); 
2

使用parse_url($url,PHP_URL_HOST)獲得主機名;然後使用以下的功能域分成幾部分:

function split_domain($host,$SLDs='co|com|edu|gov|mil|net|org') 
{ 
    $parts=explode('.',$host); 
    $index=count($parts)-1; 
    if($index>0 && in_array($parts[$index-1],explode('|',$SLDs))) $index--; 
    if($index===0) $index++; 
    $subdomain=implode('.',array_slice($parts,0,$index-1)); 
    $domain=$parts[$index-1]; 
    $tld=implode('.',array_slice($parts,$index)); 
    return array($subdomain,$domain,$tld); 
} 
7

只需使用PHP Explode Function有兩個限制。

實施例1:

var_dump(explode('.','example.com',2)); 

Resault:

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

實施例2:

var_dump(explode('.','example.uk.com',2)); 

Resault:

array(2) { [0]=> string(7) "example" [1]=> string(6) "uk.com" } 
相關問題