问题描述
让我们以这些 URL 为例:
Let's take these URLs as an example:
- http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player一个>
- http://www.youtube.com/watch?v=8GqqjVXhfMU
此 PHP 函数在第 1 种情况下无法正确获取 ID,但会在第 2 种情况下正确获取 ID.第 1 种情况非常常见,其中任何内容都可能出现在 YouTube ID 后面.
This PHP function will NOT properly obtain the ID in case 1, but will in case 2. Case 1 is very common, where ANYTHING can come behind the YouTube ID.
/**
* get YouTube video ID from URL
*
* @param string $url
* @return string YouTube video id or FALSE if none found.
*/
function youtube_id_from_url($url) {
$pattern =
'%^# Match any YouTube URL
(?:https?://)? # Optional scheme. Either http or https
(?:www.)? # Optional www subdomain
(?: # Group host alternatives
youtu.be/ # Either youtu.be,
| youtube.com # or youtube.com
(?: # Group path alternatives
/embed/ # Either /embed/
| /v/ # or /v/
| /watch?v= # or /watch?v=
) # End path alternatives.
) # End host alternatives.
([w-]{10,12}) # Allow 10-12 for 11 char YouTube id.
$%x'
;
$result = preg_match($pattern, $url, $matches);
if (false !== $result) {
return $matches[1];
}
return false;
}
我的想法是,必须有一种方法可以让我只查找v=",无论它位于 URL 的哪个位置,然后获取后面的字符.以这种方式,不需要复杂的 RegEx.这是离谱吗?对起点有什么想法吗?
What I'm thinking is that there must be a way where I can just look for the "v=", no matter where it lies in the URL, and take the characters after that. In this manner, no complex RegEx will be needed. Is this off base? Any ideas for starting points?
推荐答案
if (preg_match('/youtube.com/watch?v=([^&?/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube.com/embed/([^&?/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtube.com/v/([^&?/]+)/', $url, $id)) {
$values = $id[1];
} else if (preg_match('/youtu.be/([^&?/]+)/', $url, $id)) {
$values = $id[1];
}
else if (preg_match('/youtube.com/verify_age?next_url=/watch%3Fv%3D([^&?/]+)/', $url, $id)) {
$values = $id[1];
} else {
// not an youtube video
}
这是我用来从 youtube 网址中提取 id 的方法.我认为它适用于所有情况.
This is what I use to extract the id from an youtube url. I think it works in all cases.
注意最后 $values = 视频的 id
Note that at the end $values = id of the video
这篇关于从任何 YouTube URL 获取 YouTube 视频 ID 的 RegEx 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)