Skip to content

Instantly share code, notes, and snippets.

@leogopal
Last active July 5, 2021 15:37
Show Gist options
  • Save leogopal/b429f9700d473a55f70819dc6e5195f0 to your computer and use it in GitHub Desktop.
Save leogopal/b429f9700d473a55f70819dc6e5195f0 to your computer and use it in GitHub Desktop.
PHP function to get youtube ID from URL
<?php
function get_youtube_video_ID($youtube_video_url) {
/**
* Pattern matches
* http://youtu.be/ID
* http://www.youtube.com/embed/ID
* http://www.youtube.com/watch?v=ID
* http://www.youtube.com/?v=ID
* http://www.youtube.com/v/ID
* http://www.youtube.com/e/ID
* http://www.youtube.com/user/username#p/u/11/ID
* http://www.youtube.com/leogopal#p/c/playlistID/0/ID
* http://www.youtube.com/watch?feature=player_embedded&v=ID
* http://www.youtube.com/?feature=player_embedded&v=ID
*/
$pattern =
'%
(?:youtube # Match any youtube url www or no www , https or no https
(?:-nocookie)?\.com/ # allows for the nocookie version too.
(?:[^/]+/.+/ # Once we have that, find the slashes
|(?:v|e(?:mbed)?)/|.*[?&]v=) # Check if its a video or if embed
|youtu\.be/) # Allow short URLs
([^"&?/ ]{11}) # Once its found check that its 11 chars.
%i';
// Checks if it matches a pattern and returns the value
if (preg_match($pattern, $youtube_video_url, $match)) {
return $match[1];
}
// if no match return false.
return false;
}
?>
@whittinghamj
Copy link

Confirmed, does not get watch?v=

@Thyme1152
Copy link

Thyme1152 commented Jan 8, 2020

The pattern itself works, it just won't work with those comments in the way. Maybe the carriage returns as well, I haven't checked.
But yeah, if you change it to a single line like:
$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
then it works, at least with ?v=ID.

@greentornado
Copy link

The pattern itself works, it just won't work with those comments in the way. Maybe the carriage returns as well, I haven't checked.
But yeah, if you change it to a single line like:
$pattern = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
then it works, at least with ?v=ID.

Confirmed, this works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment