2013-10-25 49 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;' –

相关问题