我使用以下代码只是将任何URL转换为以http://
或https://
开头但是这个函数会使精确类型的url出现问题,例如
$url = 'www.youtube.com/watch?v=_ss'; // url without http://
function convertUrl ($url){
$parts = parse_url($url);
$returl = "";
if (empty($parts['scheme'])){
$returl = "http://".$parts['path'];
} else if ($parts['scheme'] == 'https'){
$returl = "https://".$parts['host'].$parts['path'];
} else {
$returl = $url;
}
return $returl;
}
$url = convertUrl($url);
echo $url;
输出
http://www.youtube.com/watch
我想要的预期输出
http://www.youtube.com/watch?v=_ss
因为我主要使用它来修复任何没有http://
的url,所以有没有任何方法可以编辑这个函数,这样它就可以传递所有带有=_
的url,如示例所示!因为它真的很烦人~谢谢
您需要获得:
$query = $parts['query'];
因为这是URL的查询部分。
你可以修改你的功能来做到这一点:
function convertUrl ($url){
$parts = parse_url($url);
$returl = "";
if (empty($parts['scheme'])){
$returl = "http://".$parts['path'];
} else if ($parts['scheme'] == 'https'){
$returl = "https://".$parts['host'].$parts['path'];
} else {
$returl = $url;
}
// Define variable $query as empty string.
$query = '';
if ($parts['query']) {
// If the query section of the URL exists, concatenate it to the URL.
$query = '?' . $parts['query'];
}
return $returl . $query;
}
http://codepad.org/bJ7pY8bg
<?php
$url1 = 'www.youtube.com/watch?v=_ss';
$url2 = 'http://www.youtube.com/watch?v=_ss';
$url3 = 'https://www.youtube.com/watch?v=_ss';
function urlfix($url) {
return preg_replace('/^.*www'./',"https://www.",$url);
}
echo urlfix($url1)."'n";
echo urlfix($url2),"'n";
echo urlfix($url3),"'n";
输出:
https://www.youtube.com/watch?v=_ss
https://www.youtube.com/watch?v=_ss
https://www.youtube.com/watch?v=_ss
如果您真正关心的只是传递的URL的第一部分,那么另一种方法如何?
$pattern = '#^http[s]?://#i';
if(preg_match($pattern, $url) == 1) { // this url has proper scheme
return $url;
} else {
return 'http://' . $url;
}