2013-09-21 78 views
-3

我在互聯網搜索,我發現對發現域名驗證碼關於查找域名

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

它適用於http://www.google.comhttp://www.google.co.uk

但它不是工作test.web.tv.

有人可以幫助我嗎?

如何找到min域名?

感謝

+0

你想得到的URL? –

+0

'parse_url()'在全局空間中設置變量,因此如果可能的話,應該避免這種情況(黑客入侵)。 $ _SERVER ...和一個搜索SO應該做的工作。 – djot

+0

我想獲取主域名,例如test.hotmail.com ==> hotmail.com或test.hotmail.com.mx ==> hotmail.com.mx或test.web.tv ==> web.tv或google .com ==> google.com – tufancakiroglu

回答

1

功能parse_url()需要一個有效的URL。在這種情況下,test.web.tv無效,因此parse_url()不會給您預期的結果。爲了解決這個問題,您可以首先檢查該網址是否有http://前綴,如果沒有,請手動添加前綴。這樣,你可以避開parse_url()的限制。

但是,我認爲使用下面的函數會更好。

function getDomain($url) 
{  
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { 
     $url = "http://" . $url; 
    } 

    $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2)); 
    return $domain; 
} 

說明:

  • 給定的URL傳遞給parse_url()PHP_URL_HOST標誌,並獲得
  • 它與.爆炸作爲分隔符完整的主機
  • 的最後兩件數組被切片 - 即。域名
  • 它加入回用implode()

測試:

echo getDomain('test.web.tv'); 

輸出:

web.tv 

Demo!

注:這是我自己的答案的修改版本here結合Alix的回答here

此功能目前不適用於.co.uk域名擴展 - 您可以輕鬆添加支票並相應地更改array_slice功能。

+0

是的,但此代碼不適用於test.hotmail.com.mx :( – tufancakiroglu