Regex for YouTube ID

This is a duplicate question, and has been answered before.

I think you will find the regexp there will also work here.

parse youtube video id using preg_match

EDIT: I noticed that it does not work for the sandalsResort URL you have at the top of your list, so you can modify the regex to the following (converted for use in JS)

var myregexp = /(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/gi;

All I did was to replace user with [^/]+

The ID is still captured in back-reference 1.


You probably don't need a regex for this. There is very little variance in the pattern, and the delimiters themselves (/, and sometimes ?, =, or #) are unchanging. I recommend you take this in steps, using plain old string manipulation to decide your next move:

  1. Split the URL on /.
  2. Ignore the http:// and www., if present.
  3. Check that the domain name is youtube.com or youtu.be.
  4. If the DN is youtu.be, the ID is the next segment. Return it and stop.
  5. Start parsing parameters. Check the next segment:
    • If it's embed, return the following segment in full.
    • If it's v, split on ? and return the first part.
    • If it's user, count four segments ahead and you'll have your ID.
    • If it's watch, split on ? and then on =.

...etc.

I don't know how many possible patterns there are for YouTube URLs, but if you have the full list of formats, you can simply build up an if/else tree around them. My main advice is just to split on / and go from there, using contextual hints in the URL to determine how to parse the rest of it.


I use this regexp: /youtu(?:.*\/v\/|.*v\=|\.be\/)([A-Za-z0-9_\-]{11})/ and it works fine for me.


It would be very messy to write a single regular expression which handles all of these possible URLs.

I would probably use an if ... else if ... else structure to determine which form the url is in and then use a smaller more specific regular expression to pull out each video ID.