使用 preg_match 解析 youtube 视频 ID [英] parse youtube video id using preg_match

查看:34
本文介绍了使用 preg_match 解析 youtube 视频 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 preg_match 解析 youtube 网址的视频 ID.我在这个网站上发现了一个似乎有效的正则表达式;

I am attempting to parse the video ID of a youtube URL using preg_match. I found a regular expression on this site that appears to work;

(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&
]+|(?<=v=)[^&
]+

如图所示:

我的 PHP 如下,但它不起作用(给出未知修饰符 '[' 错误)...

My PHP is as follows, but it doesn't work (gives Unknown modifier '[' error)...

<?
 $subject = "http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1";

 preg_match("(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=[0-9]/)[^&
]+|(?<=v=)[^&
]+", $subject, $matches);

 print "<pre>";
 print_r($matches);
 print "</pre>";

?>

干杯

推荐答案

这个正则表达式从我能找到的所有各种 URL 中获取 ID...可能还有更多,但我无法在任何地方找到它们的参考.如果您遇到不匹配的问题,请在 URL 上留言,我会尝试更新正则表达式以匹配您的 URL.

This regex grabs the ID from all of the various URLs I could find... There may be more out there, but I couldn't find reference of them anywhere. If you come across one this doesn't match, please leave a comment with the URL, and I'll try and update the regex to match your URL.

if (preg_match('%(?:youtube(?:-nocookie)?.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/s]{11})%i', $url, $match)) {
    $video_id = $match[1];
}

以下是此正则表达式匹配的 URL 示例:(在给定 URL 之后可以有更多内容将被忽略)

Here is a sample of the URLs this regex matches: (there can be more content after the given URL that will be ignored)

  • http://youtu.be/dQw4w9WgXcQ ...
  • http://www.youtube.com/embed/dQw4w9WgXcQ ...
  • http://www.youtube.com/watch?v=dQw4w9WgXcQ ...
  • http://www.youtube.com/?v=dQw4w9WgXcQ ...
  • http://www.youtube.com/v/dQw4w9WgXcQ ...
  • http://www.youtube.com/e/dQw4w9WgXcQ ...
  • http://www.youtube.com/user/username#p/u/11/dQw4w9WgXcQ ...
  • http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/0/dQw4w9WgXcQ ...
  • http://www.youtube.com/watch?feature=player_embedded&v=dQw4w9WgXcQ ...
  • http://www.youtube.com/?feature=player_embedded&v=dQw4w9WgXcQ ...

它也适用于具有上述相同选项的 youtube-nocookie.com URL.

It also works on the youtube-nocookie.com URL with the same above options.

它还将从嵌入代码(iframe 和对象标签)中的 URL 中提取 ID

It will also pull the ID from the URL in an embed code (both iframe and object tags)

这篇关于使用 preg_match 解析 youtube 视频 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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