我在网站上看到了几个不同的示例,但它并没有从所有 youtube 选项中获取 id ......例如,以下链接不适用于下面的正则表达式模式。任何帮助都会很棒。提前致谢:
如果用户访问 youtube 主页并单击其中一个他们提供此 url 的视频,它似乎就是这个: http ://www.youtube.com/watch?v=hLSoU53DXK8&feature=g-vrec
我的正则表达式将其放入数据库中:hLSoU53DXK8-vrec,我需要它而不需要-vrec。
// YOUTUBE
$youtube = $_POST['youtube'];
function getYoutubeId($youtube) {
$url = parse_url($youtube);
if($url['host'] !== 'youtube.com' &&
$url['host'] !== 'www.youtube.com'&&
$url['host'] !== 'youtu.be'&&
$url['host'] !== 'www.youtu.be')
return false;
$youtube = preg_replace('~
# Match non-linked youtube URL in the wild. (Rev:20111012)
https?:// # Required scheme. Either http or https.
(?:[0-9A-Z-]+\.)? # Optional subdomain.
(?: # Group host alternatives.
youtu\.be/ # Either youtu.be,
| youtube\.com # or youtube.com followed by
\S* # Allow anything up to VIDEO_ID,
[^\w\-\s] # but char before ID is non-ID char.
) # End host alternatives.
([\w\-]{11}) # $1: VIDEO_ID is exactly 11 chars.
(?=[^\w\-]|$) # Assert next char is non-ID or EOS.
(?! # Assert URL is not pre-linked.
[?=&+%\w]* # Allow URL (query) remainder.
(?: # Group pre-linked alternatives.
[\'"][^<>]*> # Either inside a start tag,
| </a> # or inside <a> element text contents.
) # End recognized pre-linked alts.
) # End negative lookahead assertion.
[?=&+%\w]* # Consume any URL (query) remainder.
~ix',
'$1',
$youtube);
return $youtube;
}
$youtube_id = getYoutubeId($youtube);