2013-10-25 63 views
2

我試圖讓域名和TLD從中可能會或可能不會有協議,目錄,子用戶輸入的URL字符串(無子域)文件名等運行parse_url()在一個字符串可能不包含協議

換句話說,鑑於以下任何一項:

example.com 
www.example.com 
sub.example.com 
example.com/whatever/hey.html 
http://example.com 
https://subdomain.example.com 
ftp://example.com/whatever/hey.html 

我應該永遠結束了:example.com

現在這是我在做什麼:

$hostParts = explode('.', parse_url($URL, PHP_URL_HOST)); 
$tld = array_pop($hostParts); 
$domain = array_pop($hostParts); 
$domain = $domain . "." . $tld; 

但是,如果一個URL,而不協議提供,它打破。爲什麼在這種情況下parse_url無法獲得主機?

回答

2

根據定義的URL中包含的協議或方案。檢查//,如果不存在,則將//預先存儲到字符串中。這可能與PHP < 5.4.7不同,所以如果沒有協議,可以添加http://。

+1

我可以看到,你是對的。下面是我用來做什麼的代碼: '如果(strpos($網址, 「://」!)===假&& SUBSTR($網址,0,1)= 「/」){$ URL =「 http://「。 $ URL; }' 只要把該代碼的第一行之前,和它的作品。 – brentonstrine

+0

一丁點兒簡單,也許是:'$ URL =(strpos($ urlString, 「//」)===假)? 「// $ urlString」:$ urlString;' –

相關問題