Regex to Parse Youtube Yid

Regex to parse youtube yid

(?<=v=)[a-zA-Z0-9-_]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+

This works. http://i.imgur.com/SQJW2.jpg

YouTube url id Regex

The youtube url id always contains 11 characters numbers underscores and/or dashes. This is the regexp i've used and haven't had issues with:

var re = /[a-zA-Z0-9\-\_]{11}/;
var youtubeurl = "http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index";
alert(youtubeurl.match(re));

Edit: this solution doesn't actually work 100%, the first and second url's will have issues because the regexp matches text that isn't the vid id.

Edit2: try this one:

var re = /(\?v=|\/\d\/|\/embed\/|\/v\/|\.be\/)([a-zA-Z0-9\-\_]+)/;
var urlArr = [
"http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index",
"http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o",
"http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0",
"http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s",
"http://www.youtube.com/embed/0zM3nApSvMg?rel=0",
"http://www.youtube.com/watch?v=0zM3nApSvMg",
"http://youtu.be/0zM3nApSvMg"
];
for (var i = 0; i < urlArr.length; i++) {
alert(urlArr[i].match(re)[2]);
}

http://jsfiddle.net/HfqmE/1/

Pick out part of a url with javascript regex?

str.match(/v=(.*?)(&|$)/)[1];

It looks for a v=, then the shortest string of characters (.*?), followed by either a & or the end of the string. The [1] retrieves the first grouping, giving: ysIzPF3BfpQ.

preg_match() Unknown modifier '[' help

Try the following:

<?php
$str = "http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I";
$pattern = '#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#';
preg_match($pattern, $str, $matches);
print_r($matches);
?>

Note, I'm using # as a delimiter here simply because the regular expression above contains forward slashes and escaping them makes the expression more difficult to read. This cleans it up by just a few pixels.

JavaScript: How to Strip out everything and just get the ID?

This is a job for regex:

url.match(/(\?|&)v=([^&]+)/).pop()

which, broken down, means:

url.match(
// look for "v=", preceded by either a "?" or a "&",
// and get the rest of the string until you hit the
// end or an "&"
/(\?|&)v=([^&]+)/
)
// that gives you an array like ["?v=YgFyi74DVjc", "?", "YgFyi74DVjc"];
// take the last element
.pop()

You can use this for the second form as well if you decode it first:

url = decodeURIComponent(url);

The url variable now equals "http://www.youtube.com/verify_age?next_url=http://www.youtube.com/watch?v=[YOUTUBEID]", and the regex should work.

You could put it all together in a reusable function:

function getYouTubeID(url) {
return decodeURIComponent(url)
.match(/(\?|&)v=([^&]+)/)
.pop();
}


Related Topics



Leave a reply



Submit