Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Easy little function to get the video ID from any YouTube URL.
<php
/**
* 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 <aalaap@gmail.com>
*/
function quickYouTubeId($youTubeUrl) {
return preg_match
"/(?:[\/]|v=)([a-zA-Z0-9-_]{11})/",
$youTubeUrl,
$id)
? $id[1]
: false;
}
@aalaap
Copy link
Author

aalaap commented Jul 28, 2012

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

@Jthe4th
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!

@itzmukeshy7
Copy link

itzmukeshy7 commented Aug 5, 2017

It doesn't work if the first query value is not video id like this:
https://www.youtube.com/watch?list=RDfRh_vgS2dFE&v=fRh_vgS2dFE

Works for :
https://www.youtube.com/watch?v=fRh_vgS2dFE&list=RDfRh_vgS2dFE

Can we do anything?

@aalaap
Copy link
Author

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!

@rossor10
Copy link

You left out a "(" after preg_match.

@aalaap
Copy link
Author

aalaap commented Feb 5, 2019

If anyone's still looking for this, it's now available as a provider for the excellent Faker library: https://github.com/aalaap/faker-youtube

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