Add www to url in string

╄→гoц情女王★ 提交于 2020-05-30 14:03:40

问题


I am trying to add www to php url, but I my code is not working properly in some cases:

$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

But in this case:

$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

it changed the request.


回答1:


Don't use string manipulation methods when PHP offers proper URL parsing methods:

Do this:

<?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);

Prints:

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

Example at https://eval.in/798862



来源:https://stackoverflow.com/questions/41789067/add-www-to-url-in-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!