RegEx pattern to get the YouTube video ID from any YouTube URL(用于从任何 YouTube URL 获取 YouTube 视频 ID 的 RegEx 模式)
问题描述
我们以这些网址为例:
- http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player一个>
- http://www.youtube.com/watch?v=8GqqjVXhfMU
此 PHP 函数在第 1 种情况下无法正确获取 ID,但在第 2 种情况下会正确获取.第 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 url 中提取 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 模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于从任何 YouTube URL 获取 YouTube 视频 ID 的 RegEx 模式


基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01