让我们拿这些网址作为例子:
- 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中的位置如何,然后获取其后面的字符。用这种方式,就不需要使用复杂的正则表达式了。这种想法是否正确?有没有起点的想法?