Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Easy little function to get the video ID from any YouTube URL.
* quickYouTubeId: Easy little function to get the video ID from any YouTube
* URL.
* I went through a lot of snippets that perform various kinds of RegEx and
* parse_url and what not, but I thought, since most YouTube video IDs are 11
* characters, why not just look for the only 11-character string and extract
* that? I can't think of a YouTube URL that'll foil this match. Can you?
* 2018-06-06 - fixed the problem with other non-video IDs in the URL
* 2016-12-28 - modernized and made it more PSR-2 compliant and shorter
* 2012-07-28 - fixed for underscore matching
* 2012-07-27 - first release
* @param String $youTubeUrl The URL of the video in any format supported
* by YouTube
* @return String The 11-character YouTube video ID.
* @author Aalaap Ghag <>
function quickYouTubeId($youTubeUrl) {
return preg_match
? $id[1]
: false;
Copy link

aalaap commented Jul 28, 2012

The original function didn't match underscores. D'oh! Fixed.

Copy link

Jthe4th commented Aug 27, 2014

Awesome. After many searches and experiments, this is not only the simplest solution I found, but the only one that worked!

Copy link

itzmukeshy7 commented Aug 5, 2017

It doesn't work if the first query value is not video id like this:

Works for :

Can we do anything?

Copy link

aalaap commented Jul 6, 2018

@itzmukeshy7 Slightly tricky, due to the various formats. Maybe I could make it check for v=fRh_vgS2dFE or /fRh_vgS2dFE?

Edit: Fixed it! Thanks for reporting!

Copy link

You left out a "(" after preg_match.

Copy link

aalaap commented Feb 5, 2019

If anyone's still looking for this, it's now available as a provider for the excellent Faker library:

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