2015-09-26 80 views
0

我想刪除一切從一個URL,但域。所以http://i.imgur.com/rA81kQf.jpg成爲imgur.com。parse_url和刪除子域

$url = 'http://i.imgur.com/rA81kQf.jpg'; 

$parsedurl = parse_url($url); 

$parsedurl = preg_replace('#^www\.(.+\.)#i', '$1', $parsedurl['host']); 

// now if a dot exists, grab everything after it. This removes any potential subdomain 
$parsedurl = preg_replace("/^(.*?)\.(.*)$/","$2",$parsedurl); 

上述工作,但我覺得我應該只是一個preg_replace爲此。任何想法如何我可以結合這兩個?

+1

可能重複(HTTP ://stackoverflow.com/questions/2679618/get-domain-name-not-subdomain-in-php) – Federkun

+0

http://stackoverflow.com/questions/16027102/get-domain-name-from-full-url –

回答

0

您可以使用parse_url()來獲得這樣的期望輸出,

$url = "http://i.imgur.com/rA81kQf.jpg"; 
    $parseData = parse_url($url); 
    $domain = preg_replace('/^www\./', '', $parseData['host']); 


    $array = explode(".", $domain); 

    echo (array_key_exists(count($array) - 2, $array) ? $array[count($array) - 2] : "") . "." . $array[count($array) - 1]; 

它打印的[獲取域名(不子域)在PHP]

imgur.com