1

I'm trying to get the youtube video id and replace the url with just the youtube video id. So far I found a way to get the video id, but I can't seem to remove the url.

if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
    $video_id = $match[1];
}

Examples:

   http://youtu.be/dQw4w9WgXcQ ...
   http://www.youtube.com/embed/dQw4w9WgXcQ ...
   http://www.youtube.com/watch?v=dQw4w9WgXcQ ...
   http://www.youtube.com/?v=dQw4w9WgXcQ ...
   http://www.youtube.com/v/dQw4w9WgXcQ ...
   http://www.youtube.com/e/dQw4w9WgXcQ ...
   http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ ...
   http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ ...
   http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ ...         

Note that a youtube url can also have extra params after the video id.

Much help is appreciated. Thanks!

Lion
  • 18,729
  • 22
  • 80
  • 110
user962449
  • 3,743
  • 9
  • 38
  • 53

2 Answers2

2

For all your example urls this preg_replace works. Additionally removes any params after the video ID

$videoID =  preg_replace("#[&\?].+$#", "", preg_replace("#http://(?:www\.)?youtu\.?be(?:\.com)?/(embed/|watch\?v=|\?v=|v/|e/|.+/|watch.*v=|)#i", "", $url));
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Andreas Linden
  • 12,489
  • 7
  • 51
  • 67
-1

Try this:

<?php
$url = 'http://www.youtube.com/?v=dQw4w9WgXcQ&foo=bar&test=baz';
$path = parse_url($url, PHP_URL_PATH);
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $args);
echo "http://www.youtube.com/watch?v=". $args['v'];

codepad example

Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236