让我们这些网址为例:正则表达式来从任何YouTube网址YouTube的视频ID
- http://www.youtube.com/watch?v=8GqqjVXhfMU&feature=youtube_gdata_player
- http://www.youtube.com/watch?v=8GqqjVXhfMU
这个PHP功能将无法正常获取的ID在情况1,但情况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结束。 – Bendoh 2013-06-27 20:09:47