使用preg_match解析youtube视频ID [英] parse youtube video id using preg_match
问题描述
我正在尝试使用preg_match解析youtube URL的视频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]/)[^&\n]+|(?<=v=)[^&\n]+
如下图所示:
我的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]/)[^&\n]+|(?<=v=)[^&\n]+", $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 ...
- 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网址上使用上述相同的选项.
It also works on the youtube-nocookie.com URL with the same above options.
它还会从嵌入代码(iframe和对象代码)的网址中提取ID
It will also pull the ID from the URL in an embed code (both iframe and object tags)
这篇关于使用preg_match解析youtube视频ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!