How to Alter This Regex to Get the Youtube Video Id from a Youtube Url That Doesn't Specify the V Parameter

RegEx pattern to get the YouTube video ID from any YouTube URL

if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
}
else if (preg_match('/youtube\.com\/verify_age\?next_url=\/watch%3Fv%3D([^\&\?\/]+)/', $url, $id)) {
$values = $id[1];
} else {
// not an youtube video
}

This is what I use to extract the id from an youtube url. I think it works in all cases.

Note that at the end $values = id of the video

How do I get the YouTube video ID from a URL?

You don't need to use a regular expression for this.

var video_id = window.location.search.split('v=')[1];
var ampersandPosition = video_id.indexOf('&');
if(ampersandPosition != -1) {
video_id = video_id.substring(0, ampersandPosition);
}

PHP Regex to get youtube video ID?

Use parse_url() and parse_str().

(You can use regexes for just about anything, but they are very easy to make an error in, so if there are PHP functions specifically for what you are trying to accomplish, use those.)

parse_url takes a string and cuts it up into an array that has a bunch of info. You can work with this array, or you can specify the one item you want as a second argument. In this case we're interested in the query, which is PHP_URL_QUERY.

Now we have the query, which is v=C4kxS1ksqtw&feature=relate, but we only want the part after v=. For this we turn to parse_str which basically works like GET on a string. It takes a string and creates the variables specified in the string. In this case $v and $feature is created. We're only interested in $v.

To be safe, you don't want to just store all the variables from the parse_url in your namespace (see mellowsoon's comment). Instead store the variables as elements of an array, so that you have control over what variables you are storing, and you cannot accidentally overwrite an existing variable.

Putting everything together, we have:

<?php
$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=relate";
parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
echo $my_array_of_vars['v'];
// Output: C4kxS1ksqtw
?>

Working example


Edit:

hehe - thanks Charles. That made me laugh, I've never seen the Zawinski quote before:

Some people, when confronted with a problem, think ‘I know, I’ll use regular expressions.’ Now they have two problems.
Jamie Zawinski

Regex for youtube URL

  • You're missing www in your regex
  • The second \. should optional if you want to match both youtu.be and youtube (but I didn't change this since just youtube isn't actually a valid domain - see note below)
  • + in your regex allows for one or more of (youtube\.com|youtu\.be), not one or more wild-cards.

    You need to use a . to indicate a wild-card, and + to indicate you want one or more of them.

Try:

^(https?\:\/\/)?(www\.youtube\.com|youtu\.be)\/.+$

Live demo.

If you want it to match URLs with or without the www., just make it optional:

^(https?\:\/\/)?((www\.)?youtube\.com|youtu\.be)\/.+$

Live demo.

Invalid alternatives:

If you want www.youtu.be/... to also match (at the time of writing, this doesn't appear to be a valid URL format), put the optional www. outside the brackets:

^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.be)\/.+$

youtube/cCnrX1w5luM (with or without http://) isn't a valid URL, but the question explicitly mentions that the regex should support that. To include this, replace youtu\.be with youtu\.?be in any regex above. Live demo.

How to use gsub to extract the id of a youtube video?

You can match the v parameter with this regexp:

url[/(?<=[?&]v=)[^&$]+/] # => aNdMiIAlK0g

It starts with a lookbehind for ? or & and matches everything up until the next & or the end of the string. It works even if there are other parameters, even those ending in "v".

However, a safer way to do it might be to use the URI class:

require 'uri'

query_string = URI.parse(url).query
parameters = Hash[URI.decode_www_form(query_string)]
parameters['v'] # => aNdMiIAlK0g

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.

Regular expression for youtube links

So far I got this Regular expression working for the examples I posted, and it gets the ID on the first group:

http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?

Regex to extract domain and video id from youtube/vimeo url

The .+$ at the end is requiring at least one character after the last digit that is captured as a string of digits. That will chop one digit off what is captured. Is there a reason you have that there?

You can change the last + to a * like this:

/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+)).*$/

or even better, get rid of the end part entirely since it doesn't look like it's needed:

/^http:\/\/(?:.*?)\.?(youtube|vimeo)\.com\/(watch\?[^#]*v=(\w+)|(\d+))/

Here's a bit safer way to write your function that allows for any order of the query parameters in the youtube URL and doesn't put stuff into the regex that doesn't need to be there. The code is longer, but it's much more robust and would be much easier to add more providers:

function parseVideoURL(url) {

function getParm(url, base) {
var re = new RegExp("(\\?|&)" + base + "\\=([^&]*)(&|$)");
var matches = url.match(re);
if (matches) {
return(matches[2]);
} else {
return("");
}
}

var retVal = {};
var matches;

if (url.indexOf("youtube.com/watch") != -1) {
retVal.provider = "youtube";
retVal.id = getParm(url, "v");
} else if (matches = url.match(/vimeo.com\/(\d+)/)) {
retVal.provider = "vimeo";
retVal.id = matches[1];
}
return(retVal);
}

Working version here: http://jsfiddle.net/jfriend00/N2hPj/



Related Topics



Leave a reply



Submit