Grab the video ID only from youtube's URLs

夙愿已清 提交于 2019-12-02 02:55:24

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
echo $query['feature'] // grec_index

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!