views:

49

answers:

2

How can I grab the video ID only from the youtube's URLs?

For instance,

http://www.youtube.com/watch?v=aPm3QVKlBJg

sometime the URLs contain other information after the 'v' like

http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index

but I don't want the other info, just video ID.

I only can think of using explode,

$url  = "http://www.youtube.com/watch?v=aPm3QVKlBJg";
$pieces = explode("v=", $url);

but how to clean up the URLs like this?

http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index

A: 

Exact duplicate, http://stackoverflow.com/questions/2984257/php-how-to-convert-the-youtube-url-with-regex

PHP:

preg_replace('/.+(\?|&)v=([a-zA-Z0-9]+).*/', 'http://youtube.com/watch?v=$2', 'http://www.youtube.com/watch?v=136pEZcb1Y0&feature=fvhl');
Orbit
+7  A: 

You should never use regular expressions when the same thing can be accomplished through purpose-built functions.

You can use parse_url to break the URL up into its segments, and parse_str to break the query string portion into a key/value array:

$url = 'http://www.youtube.com/watch?v=Z29MkJdMKqs&feature=grec_index'

// break the URL into its components
$parts = parse_url($url);

// $parts['query'] contains the query string: 'v=Z29MkJdMKqs&feature=grec_index'

// parse variables into key=>value array
$query = array();
parse_str($parts['query'], $query);

echo $query['v']; // Z29MkJdMKqs

The alternate form of parse_str extracts variables into the current scope. You could build this into a function to find and return the v parameter:

// Returns null if video id doesn't exist in URL
function get_video_id($url) {
  $parts = parse_url($url);

  // Make sure $url had a query string
  if (!array_key_exists('query', $parts))
    return null;

  parse_str($parts['query']);

  // Return the 'v' parameter if it existed
  return isset($v) ? $v : null;
}
meagar
thanks so much for this! its beautiful! :-)
lauthiamkok