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;
}