Skip to content

Instantly share code, notes, and snippets.

@ghalusa
Created June 20, 2015 23:14
Show Gist options
  • Save ghalusa/6c7f3a00fd2383e5ef33 to your computer and use it in GitHub Desktop.
Save ghalusa/6c7f3a00fd2383e5ef33 to your computer and use it in GitHub Desktop.
Extract the YouTube Video ID from a URL in PHP
<?php
// 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)
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
$youtube_id = $match[1];
?>
@ghalusa
Copy link
Author

ghalusa commented May 19, 2020

@ijyoung Not a problem! Apologies for not being able to answer right away.

@ijyoung
Copy link

ijyoung commented May 19, 2020

Thanks for reply.. Much appreciated.

@trevorhawes
Copy link

@praveen-vishnu
Copy link

Thanx for posting

@webwayscript
Copy link

embed/live_stream?channel=UCmyKnNRH0wH-r8I-ceP-dsg ???????

@stell
Copy link

stell commented May 6, 2021

@irfan-dahir
Copy link

@harihar-w
Copy link

harihar-w commented Sep 29, 2023

Not working on https://youtube.com/live/…
Edit:
just added |live/ works for me now:

preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=|live/)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
    $youtube_id = $match[1];

@neurotic
Copy link

Not working on https://youtube.com/live/… Edit: just added |live/ works for me now:

preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=|live/)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match);
    $youtube_id = $match[1];

Works perfect, thanks!

@petemolinero
Copy link

I visited the YouTube URL in your code sample hoping for a very specific video, and I was not disappointed.

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