我们以这些 URL 为例:
- 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 后面。
/**
* 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。这是离谱吗?对起点有什么想法吗?
最佳答案
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 的方法。我认为它适用于所有情况。
注意最后 $values = 视频的id
关于php - 从任何 YouTube URL 获取 YouTube 视频 ID 的正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594943/