Reputation: 5063
I'm using the following code just to convert any URL to starts with http://
or https://
but this function makes problem with exact type urls as example
$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;
the output
http://www.youtube.com/watch
expected output as i want
http://www.youtube.com/watch?v=_ss
as i mainly use it just to fix any url without http://
so is there any way to edit this function so it can pass all urls with =_
as shown in the example ! as it really annoying me ~ thanks
Upvotes: 0
Views: 395
Reputation: 71384
If all you really care about is the first part of the passed URL, how about an alternate approach?
$pattern = '#^http[s]?://#i';
if(preg_match($pattern, $url) == 1) { // this url has proper scheme
return $url;
} else {
return 'http://' . $url;
}
Upvotes: 2
Reputation: 8059
<?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";
Output:
https://www.youtube.com/watch?v=_ss
https://www.youtube.com/watch?v=_ss
https://www.youtube.com/watch?v=_ss
Upvotes: 2
Reputation: 4024
You'll want to get:
$query = $parts['query'];
Because that's the query section of the URL.
You can modify your function to do this:
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;
}
Upvotes: 5