2010-12-07 30 views

回答

2

只需使用parse_url()如果你正在專門處理網址。

例如:

$url = "http://www.hegnar.no/bors/article488276.ece"; 
$url_u_want = parse_url($url, PHP_URL_HOST); 

Docs

編輯: 取出萬維網。盈方,用途:

$url_u_want = preg_replace("/^www\./", "", $url_u_want); 
7

您不需要爲此任務使用regexp。

檢查PHP的內置功能,parse_url http://php.net/manual/en/function.parse-url.php

+0

當URL沒有www時,它返回null。或http – 2010-12-07 16:03:46

+0

什麼返回false?鏈接到PHP手冊? – 2010-12-07 16:06:00

+0

該功能。如果URL沒有www,則返回null。 – 2010-12-07 16:08:11

1
$host = parse_url($url, PHP_URL_HOST); 
$host = array_reverse(explode('.', $host)); 
$host = $host[1].'.'.$host[0]; 
2
$page = "http://google.no/page/page_1.html"; 
preg_match_all("/((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])/", $page, $result, PREG_PATTERN_ORDER); 

print_r($result); 
0

這是問題,當你使用parse_url,在$網址沒有.com或.net或等則返回的結果爲bannedadsense,這意味着返回true,事實bannedadsense不是域。

$url = 'http://bannedadsense/isbanned'; // this url will return false in preg_match 
//$url = 'http://bannedadsense.com/isbanned'; // this url will return domain in preg_match 
$domain = parse_url($url, PHP_URL_HOST)); 
// return "bannedadsense", meaning this is right domain. 

所以,我們需要繼續沒有點擴展名(.com,.net和.org和等)

if(preg_match("/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/i",$domain)) { 
    echo $domain; 
}else{ 
    echo "<br>"; 
    echo "false"; 
}