将 www 添加到字符串中的 url [英] Add www to url in string

查看:28
本文介绍了将 www 添加到字符串中的 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 www 添加到 php url,但我的代码在某些情况下无法正常工作:

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

但在这种情况下:

$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

它改变了请求.

推荐答案

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

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

这样做:

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

这篇关于将 www 添加到字符串中的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆