我正在使用以下代码只是为了将任何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;
Run Code Online (Sandbox Code Playgroud)
输出
http://www.youtube.com/watch
Run Code Online (Sandbox Code Playgroud)
我想要的预期产量
http://www.youtube.com/watch?v=_ss
Run Code Online (Sandbox Code Playgroud)
因为我主要使用它只是为了修复任何网址没有http://这样有任何方法来编辑这个功能所以它可以传递所有网址,=_如示例所示!因为它真的很烦我〜谢谢
你会想得到:
$query = $parts['query'];
Run Code Online (Sandbox Code Playgroud)
因为那是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;
}
Run Code Online (Sandbox Code Playgroud)