RegEx pattern to get the YouTube video ID from any YouTube URL
if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
}
else if (preg_match('/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else {
// not an youtube video
}
This is what I use to extract the id from an youtube url. I think it works in all cases.
Note that at the end $values = id of the video
Instead of regex. I hightly recommend parse_url()
and parse_str()
:
$url = "http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player";
parse_str(parse_url( $url, PHP_URL_QUERY ), $vars );
echo $vars['v'];
Done
You could just use parse_url
and parse_str
:
$query_string = parse_url($url, PHP_URL_QUERY);
parse_str($query_string);
echo $v;
I have used the following patterns because YouTube has a youtube-nocookie.com domain too:
'@youtube(?:-nocookie)?\.com/watch[#\?].*?v=([^"\& ]+)@i',
'@youtube(?:-nocookie)?\.com/embed/([^"\&\? ]+)@i',
'@youtube(?:-nocookie)?\.com/v/([^"\&\? ]+)@i',
'@youtube(?:-nocookie)?\.com/\?v=([^"\& ]+)@i',
'@youtu\.be/([^"\&\? ]+)@i',
'@gdata\.youtube\.com/feeds/api/videos/([^"\&\? ]+)@i',
In your case it would only mean to extend the existing expressions with an optional (-nocookie) for the regular YouTube.com URL like so:
if (preg_match('/youtube(?:-nocookie)\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
If you change your proposed expression to NOT contain the final $, it should work like you intended. I added the -nocookie as well.
/**
* get YouTube video ID from URL
*
* @param string $url
* @return string YouTube video id or FALSE if none found.
*/
function youtube_id_from_url($url) {
$pattern =
'%^# Match any YouTube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www\.)? # Optional www subdomain
(?: # Group host alternatives
youtu\.be/ # Either youtu.be,
|youtube(?:-nocookie)?\.com # or youtube.com and youtube-nocookie
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch\?v= # or /watch\?v=
) # End path alternatives.
) # End host alternatives.
([\w-]{10,12}) # Allow 10-12 for 11 char YouTube id.
%x'
;
$result = preg_match($pattern, $url, $matches);
if (false !== $result) {
return $matches[1];
}
return false;
}