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:
- Split the URL on
/
. - Ignore the
http://
andwww.
, if present. - Check that the domain name is
youtube.com
oryoutu.be
. - If the DN is
youtu.be
, the ID is the next segment. Return it and stop. - 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=
.
- If it's
...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.