我在网站上看到了几个不同的示例,但它没有从所有youtube选项中获取id ...作为示例,以下链接不适用于下面的正则表达式模式。任何帮助都会很精彩。提前致谢:
如果用户访问youtube主页并点击其中一个视频,他们会给出此网址,这似乎就是这个: 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);
答案 0 :(得分:14)
$url = "http://www.youtube.com/watch?v=hLSoU53DXK8&feature=g-vrec";
$query_string = array();
parse_str(parse_url($url, PHP_URL_QUERY), $query_string);
$id = $query_string["v"];
答案 1 :(得分:3)
不幸的是,上面的解决方案没有检索短网址“http://youtu.be”的Youtube ID。所以根据上面的解决方案,我写了这个函数:
function get_youtube_id( $youtube_url ) {
$url = parse_url($youtube_url);
if( $url['host'] !== 'youtube.com' &&
$url['host'] !== 'www.youtube.com'&&
$url['host'] !== 'youtu.be'&&
$url['host'] !== 'www.youtu.be')
return '';
if( $url['host'] === 'youtube.com' || $url['host'] === 'www.youtube.com' ) :
parse_str(parse_url($youtube_url, PHP_URL_QUERY), $query_string);
return $query_string["v"];
endif;
$youtube_id = substr( $url['path'], 1 );
if( strpos( $youtube_id, '/' ) )
$youtube_id = substr( $youtube_id, 0, strpos( $youtube_id, '/' ) );
return $youtube_id;
}
答案 2 :(得分:0)
$youtube = "theURL";
$query_string = array();
parse_str(parse_url($youtube, PHP_URL_QUERY), $query_string);
$youtube_id = $query_string["v"];