PHP正则表达式获取YouTube视频ID?

162

有人可以向我展示如何从URL中获取YouTube ID,而不管URL中包含了什么其他GET变量。

以此视频为例:http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related
因此在v=和下一个&之间就是YouTube ID。


1
那可能会有帮助。 获取YouTube视频ID的PHP代码: - user1331642
1
你应该看一下我的代码https://github.com/lingtalfi/video-ids-and-thumbnails/blob/master/testvideo.php,我提供了从YouTube、Vimeo和Dailymotion提取ID的函数。 - ling
在函数getVideoThumbnailByUrl()中,您使用了已弃用的file_get_contents()来获取Vimeo的缩略图。以下替代方法可以在任何地方使用:$ch=curl_init(); curl_setopt($ch, CURLOPT_URL, "http://vimeo.com/api/v2/video/$id.php"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); $hash =unserialize(curl_exec($ch)); curl_close($ch); - jerrygarciuh
@ling 在getYoutubeId($url)中,最后的条件语句将接受任何字符串并将其验证为YT id。我传递了'junk',它返回从该字符串解析出的id 'junk'。 - jerrygarciuh
@jerrygarciuh:据我所知,file_get_contents函数并没有被弃用,请随时在GitHub上报告问题,如果您在使用此函数时遇到问题。感谢您发现getYoutubeId中的错误(我已经对其进行了改进)。 - ling
@ling - 你说得对。正确的表达应该是,file_get_contents函数经常被主机禁用,因为存在安全风险。 - jerrygarciuh
19个回答

5
if (preg_match('![?&]{1}v=([^&]+)!', $url . '&', $m))
    $video_id = $m[1];

谢谢,这对我很有用,因为我想要所有的域名、http和https以及URL中的任何其他垃圾。 - MakuraYami

5

我有一些文章内容需要解密,以获取Youtube视频ID。它恰好是由Youtube提供的<iframe>嵌入代码形式。

 <iframe src="http://www.youtube.com/embed/Zpk8pMz_Kgw?rel=0" frameborder="0" width="620" height="360"></iframe>

我从@rob那里得到了以下模式。一旦找到匹配项,片段将执行foreach循环,并为额外的奖励,我将其链接到在Youtube上找到的预览图片。它有可能匹配更多类型的Youtube嵌入类型和网址:
$pattern = '#(?<=(?:v|i)=)[a-zA-Z0-9-]+(?=&)|(?<=(?:v|i)\/)[^&\n]+|(?<=embed\/)[^"&\n]+|(?<=‌​(?:v|i)=)[^&\n]+|(?<=youtu.be\/)[^&\n]+#';

preg_match_all($pattern, $post_content, $matches);

foreach ($matches as $match) {
    $img = "<img src='http://img.youtube.com/vi/".str_replace('?rel=0','', $match[0])."/0.jpg' />";
    break;
}

Rob的个人资料: https://stackoverflow.com/users/149615/rob


(说明:此为原文内容,无需翻译)

3
$vid = preg_replace('/^.*(\?|\&)v\=/', '', $url);  // Strip all meuk before and including '?v=' or '&v='.

$vid = preg_replace('/[^\w\-\_].*$/', '', $vid);  // Strip trailing meuk.

2

我知道这个帖子的标题涉及到正则表达式的使用,但正如Zawinski所说,我认为在这里避免使用正则表达式是最好的选择。我建议使用这个函数代替:

function get_youtube_id($url)
{
    if (strpos( $url,"v=") !== false)
    {
        return substr($url, strpos($url, "v=") + 2, 11);
    }
    elseif(strpos( $url,"embed/") !== false)
    {
        return substr($url, strpos($url, "embed/") + 6, 11);
    }

}

我推荐这种做法是因为YouTube视频的ID始终保持不变,与URL的样式无关,例如:
  • http://www.youtube.com/watch?v=t_uW44Bsezg
  • http://www.youtube.com/watch?feature=endscreen&v=Id3xG4xnOfA&NR=1
  • `以及其他在ID之前放置单词"embed/"的URL格式...!!
而且这也适用于嵌入和iframe的内容。

2

使用以下代码:

$url = "http://www.youtube.com/watch?v=C4kxS1ksqtw&feature=related"; 
$parse = parse_url($url, PHP_URL_QUERY); 
parse_str($parse, $output); 
echo $output['watch'];

result : C4kxS1ksqtw


0

刚在http://snipplr.com/view/62238/get-youtube-video-id-very-robust/上发现了这个。

function getYouTubeId($url) {
// Format all domains to http://domain for easier URL parsing
str_replace('https://', 'http://', $url);
if (!stristr($url, 'http://') && (strlen($url) != 11)) {
    $url = 'http://' . $url;
}
$url = str_replace('http://www.', 'http://', $url);

if (strlen($url) == 11) {
    $code = $url;
} else if (preg_match('/http:\/\/youtu.be/', $url)) {
    $url = parse_url($url, PHP_URL_PATH);
    $code = substr($url, 1, 11);
} else if (preg_match('/watch/', $url)) {
    $arr = parse_url($url);
    parse_str($url);
    $code = isset($v) ? substr($v, 0, 11) : false;
} else if (preg_match('/http:\/\/youtube.com\/v/', $url)) {
    $url = parse_url($url, PHP_URL_PATH);
    $code = substr($url, 3, 11);
} else if (preg_match('/http:\/\/youtube.com\/embed/', $url, $matches)) {
    $url = parse_url($url, PHP_URL_PATH);
    $code = substr($url, 7, 11);
} else if (preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&\n]+|(?<=v=)[^&\n]+#", $url, $matches) ) {
    $code = substr($matches[0], 0, 11);
} else {
    $code = false;
}

if ($code && (strlen($code) < 11)) {
    $code = false;
}

return $code;
}

0

如果我想从一个充满其他字符的字符串中提取YouTube网址怎么办? 例如:

Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。 Ut enim ad minim veniam,quis nostrud exercitation ullamcohttps://www.youtube.com/watch?v=cPW9Y94BJI0 laboris nisi ut aliquip ex ea commodo consequat。 Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur。 Excepteur sint occaecat cupidatat non proident,sunt in culpa qui officia deserunt mollit anim id est laborum。

如何从该字符串中获取https://www.youtube.com/watch?v=cPW9Y94BJI0


0
我使用了Shawn's answer的数据,但是将正则表达式泛化并缩短了一点。与此不同的关键是,它不会测试有效的Youtube URL,而只是查找视频ID。这意味着它仍然会返回www.facebook.com?wtv=youtube.com/v/vidid的视频ID。适用于所有测试用例,但要宽松一些。因此,对于像https://www.twitter.com/watch?v=vidid这样的内容,它将输出虚假信息。如果数据非常不一致,请使用此方法,否则请使用更具体的正则表达式或 parse_url()parse_str()
preg_match("/([\?&\/]vi?|embed|\.be)[\/=]([\w-]+)/",$url,$matches);
print($matches[2]);

0

我想你是在尝试这样做。

<?php
  $video = 'https://www.youtube.com/watch?v=u00FY9vADfQ';
  $parsed_video = parse_url($video, PHP_URL_QUERY);
  parse_str($parsed_video, $arr);
?>
<iframe
src="https://www.youtube.com/embed/<?php echo $arr['v'];  ?>"
frameborder="0">
</iframe>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接