Skip to content

Instantly share code, notes, and snippets.

@afeld
Created September 30, 2011 20:28
Show Gist options
  • Save afeld/1254889 to your computer and use it in GitHub Desktop.
Save afeld/1254889 to your computer and use it in GitHub Desktop.
YouTube video ID regex
# Parses YouTube URLs directly or from iframe code. Handles:
# * Address bar on YouTube url (ex: http://www.youtube.com/watch?v=ZFqlHhCNBOI)
# * Direct http://youtu.be/ url (ex: http://youtu.be/ZFqlHhCNBOI)
# * Full iframe embed code (ex: <iframe src="http://www.youtube.com/embed/ZFqlHhCNBOI">)
# * Old <object> tag embed code (ex: <object><param name="movie" value="http://www.youtube.com/v/ZFqlHhCNBOI">...)
/(youtu\.be\/|youtube\.com\/(watch\?(.*&)?v=|(embed|v)\/))([^\?&"'>]+)/
$5 #=> the video ID
# test it on Rubular: http://rubular.com/r/eaJeSMkJvo
@dgilperez
Copy link

@toots it works for me removing the last \W

@rolfen
Copy link

rolfen commented Feb 16, 2018

Same thing for php - must remove trailing \W. I also had to enclose it in slashes /.

@axelwehner
Copy link

Thanks, I use it in PHP:

function getYoutubeId($url)
{
    // original regex source: https://gist.github.com/afeld/1254889#gistcomment-1253992
    $regex = '/(?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/mi';
    preg_match($regex, $url, $matches);
    return isset($matches[1]) ? $matches[1] : null;
}

$url = 'https://www.youtube.com/watch?v=SN102svZHQg';
echo getYoutubeId($url); // SN102svZHQg

@Jimbolino
Copy link

private const MAGIC_REGEX = '#^(?:https?://|//)?(?:www\.|m\.|.+\.)?(?:youtu\.be/|youtube\.com/(?:embed/|v/|shorts/|feeds/api/videos/|watch\?v=|watch\?.+&v=))([\w-]{11})(?![\w-])#';

added support for shorts :)

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