2017-01-22 21 views
1

我试图WWW添加到PHP的网址,但我我的代码是不是在某些情况下正常工作:加上www到URL字符串

$url="http://example.com"; 
$url=str_replace(array("http://www.","https://www."),array("http://","https://"),$url); 
$url=str_replace(array("http://","https://"),array("http://www.","https://www."),$url); 
echo $url; //http://www.example.com 

但在这种情况下:

$url="https://www.example.com/href.php?redir=http://other-nonwww-server.com"; 
$url=str_replace(array("http://www.","https://www."),array("http://","https://"),$url); 
$url=str_replace(array("http://","https://"),array("http://www.","https://www."),$url); 
echo $url; //https://www.example.com/href.php?redir=http://www.other-nonwww-server.com 

它改变了请求。

回答

2

PHP提供适当的URL解析方法时,不要使用字符串操作方法:

这样做:

<?php 
$url="https://example.com:8080/href.php?redir=http://other-nonwww-server.com"; 

$bits = parse_url($url); 

$newHost = substr($bits["host"],0,4) !== "www."?"www.".$bits["host"]:$bits["host"]; 

$url2 = $bits["scheme"]."://".$newHost.(isset($bits["port"])?":".$bits["port"]:"").$bits["path"].(!empty($bits["query"])?"?".$bits["query"]:"");; 

print_r($url2); 

打印:

https://www.example.com:8080/href.php?redir=http://other-nonwww-server.com 

例在https://eval.in/798862

+0

这并未似乎没有考虑带有端口的URL,例如http:// localhost:8080 /。 – Shaun

+0

@Shaun好点。更新。 – apokryfos