【发布时间】:2012-03-24 14:16:57
【问题描述】:
我们以这些网址为例:
- 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。这是离谱吗?关于起点的任何想法?
【问题讨论】:
-
我认为这种模式的主要问题只是模式末尾的 $ ,它将模式锚定在被测试字符串的末尾。这就是案例 1 不匹配的原因,因为它不以 ID 结尾。
标签: php regex youtube youtube-api