仅从YouTube的网址中获取视频ID [英] Grab the video ID only from youtube's URLs

查看:143
本文介绍了仅从YouTube的网址中获取视频ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何仅从youtube的网址中获取视频ID?

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

例如,

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

有时,URL包含'v'之后的其他信息,例如

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

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

但是我不想要其他信息,只是视频ID.

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

我只能想到使用爆炸

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

但是如何清理这样的URL?

but how to clean up the URLs like this?

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

推荐答案

如果可以通过专用函数完成相同的事情,则永远不要使用正则表达式.

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

您可以使用 parse_url 来断开URL细分为各个细分,然后 parse_str 来中断查询字符串部分放入键/值数组:

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

parse_str的替代形式将变量提取到当前作用域中.您可以将其内置到一个函数中,以查找并返回v参数:

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

这篇关于仅从YouTube的网址中获取视频ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆