Skip to content

Instantly share code, notes, and snippets.

@dospuntocero
Forked from leogopal/youtube-id.php
Created March 3, 2019 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dospuntocero/6c89229c4b8ac1f93b12b50031808827 to your computer and use it in GitHub Desktop.
Save dospuntocero/6c89229c4b8ac1f93b12b50031808827 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;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment