Reputation: 4695
function getYoutubeVideoId($url) {
$urlParts = parse_url($url);
if($urlParts === false)
return false;
if(isset($urlParts['host']) && strtolower($urlParts['host']) === 'youtu.be')
return ltrim($urlParts['path'], '/');
if(isset($urlParts['query'])) {
parse_str($urlParts['query'], $queryParts);
if(isset($queryParts['v']))
return $queryParts['v'];
}
return false;
}
This function works great.. unless you use youtu.be/*
without http://
Why does it not work if it is just youtu.be
or www.youtu.be
?
Upvotes: 2
Views: 119
Reputation: 4695
This seems to work:
function getYoutubeVideoId($url) {
$url = str_replace('http://', '', $url);
$url = str_replace('www.', '', $url);
$urlParts = parse_url($url);
if($urlParts === false){
return false;
}
if(strstr($urlParts['path'], 'youtu.be')){
return str_replace('youtu.be/', '', $urlParts['path']);
}
if(isset($urlParts['query'])) {
parse_str($urlParts['query'], $queryParts);
if(isset($queryParts['v'])){
return $queryParts['v'];
}
}
return false;
}
Upvotes: 0
Reputation: 70490
if(
(isset($urlParts['host']) && strtolower($urlParts['host']) === 'youtu.be'))
||
(!isset($urlParts['host'] && strstr($urlParts['path'],'/',true)=='youtu.be')
Upvotes: 0
Reputation: 9875
The parse_url() function specifically does not validate the url, which is why your code would break.
Try using preg_match() and a regex to validate the url first.
Upvotes: 0
Reputation: 129011
Look what it returns for that input:
php> =parse_url('youtu.be/id')
array(
"path" => "youtu.be/id",
)
Perhaps if host
isn't set on the result, try re-parsing with http://
prepended.
Upvotes: 1
Reputation: 98479
Technically, youtu.be/foo
is not a URL. A URL must have a scheme at the start, followed by ://
.
So the reason it isn't working is because you're giving the parse_url
function invalid input. You must clean it up first.
Upvotes: 4
Reputation: 4729
I just use:
function getYoutubeId($url){
$parsed = parse_url($url);
parse_str($parsed['query']);
return $v;
}
Not sure if that helps...
Upvotes: 0