Skip to content

Instantly share code, notes, and snippets.

@fazlurr
Created August 14, 2019 05:07
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 fazlurr/bab6e6389d52cc789047faeb551fa3b3 to your computer and use it in GitHub Desktop.
Save fazlurr/bab6e6389d52cc789047faeb551fa3b3 to your computer and use it in GitHub Desktop.
<?php
/**
* @param string $url
* @see https://stackoverflow.com/a/51246730/5627904
*/
function get_youtube_id($url) {
// Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)
// http://youtu.be/dQw4w9WgXcQ
// http://www.youtube.com/embed/dQw4w9WgXcQ
// http://www.youtube.com/watch?v=dQw4w9WgXcQ
// http://www.youtube.com/?v=dQw4w9WgXcQ
// http://www.youtube.com/v/dQw4w9WgXcQ
// http://www.youtube.com/e/dQw4w9WgXcQ
// http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ
// http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ
// http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ
// http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ
// It also works on the youtube-nocookie.com URL with the same above options.
// It will also pull the ID from the URL in an embed code (both iframe and object tags)
// $url = "https://www.youtube.com/watch?v=v2_MLFVdlQM";
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = isset($match[1]) ? $match[1] : '';
return $youtube_id;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment