0

Possible Duplicate:
parse youtube video id using preg_match
Grab the video ID only from youtube's URLs

I use something like this now but i get a lot of errors...

$video_id = $_GET['url'];

$video_id = str_replace('http://www.youtube.com/watch?v=','',$video_id);
$video_id = str_replace('&feature=related','',$video_id);
$video_id = str_replace('&feature=fvwrel','',$video_id);
$video_id = str_replace('&hd=1','',$video_id);
$video_id = str_replace('&feature=relmfu','',$video_id);
$video_id = str_replace('&feature=channel_video_title','',$video_id);
$video_id = str_replace('&feature=list_related','',$video_id);
$video_id = str_replace('&playnext=1','',$video_id);
$video_id = str_replace('_player','',$video_id);

The problem is that youtube has multiple url variables for '&feature=' and maybe others

The only thing i want to extract from the youtube url is the unique video id

ex: //www.youtube.com/watch?v=lgT1AidzRWM&feature=related

and nothing after the id or before

can someone help me to get it?

Community
  • 1
  • 1
m3tsys
  • 3,939
  • 6
  • 31
  • 45

5 Answers5

8

What you can do is this:

$url = "http://www.youtube.com/watch?v=lgT1AidzRWM&feature=related";
$p_url = parse_url($url);
parse_str($p_url['query'], $p_param);
print_r($p_param['v']);

Example: http://codepad.org/BiWKxfSZ

Naftali
  • 144,921
  • 39
  • 244
  • 303
3
$video_id = parse_url($video_id);    
parse_str($video_id['query'], $video_id);
echo $video_id['v'];
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
1

I would use regular expressions

preg_match("/v=(\w+)/", $video_id, $matches);
print_r($matches);
Zach
  • 9,591
  • 1
  • 38
  • 33
0

You're better of using a regular expression for this. Untested:

if(preg_match('/[\?&]v=([^&]*?)/', $video_id, $match))
{
    $video_id = $match[1];
}
else exit('video id not found');
matthiasmullie
  • 2,063
  • 15
  • 17
0

using preg_match would be the most efficient way for this you can search the string for watch?v= up to the & or special char and place that into a variable.

this should help

http://php.net/manual/en/function.preg-match.php

Daniel Benzie
  • 479
  • 1
  • 5
  • 27