获取 youtube 视频 ID 为 PHP
我目前正在编写一个 web 应用程序,其中一些页面严重依赖于能够将正确的 youtube 视频拉入并播放.youtube URL 由用户提供,因此通常会带有变体,其中之一可能如下所示:
I am currently writing a webapp in which some pages are heavily reliant on being able to pull the correct youtube video in - and play it. The youtube URLS are supplied by the users and for this reason will generally come in with variants one of them may look like this:
http://www.youtube.com/watch?v=y40ND8kXDlg
而另一个可能看起来像这样:
while the other may look like this:
http://www.youtube.com/watch/v/y40ND8kXDlg
目前我可以使用以下代码从后者中提取 ID:
Currently I am able to pull the ID from the latter using the code below:
function get_youtube_video_id($video_id)
{
// Did we get a URL?
if ( FALSE !== filter_var( $video_id, FILTER_VALIDATE_URL ) )
{
// http://www.youtube.com/v/abcxyz123
if ( FALSE !== strpos( $video_id, '/v/' ) )
{
list( , $video_id ) = explode( '/v/', $video_id );
}
// http://www.youtube.com/watch?v=abcxyz123
else
{
$video_query = parse_url( $video_id, PHP_URL_QUERY );
parse_str( $video_query, $video_params );
$video_id = $video_params['v'];
}
}
return $video_id;
}
如何处理使用 ?v
版本而不是 /v/
版本的 URL?
How can I deal with URLS that use the ?v
version rather than the /v/
version?
推荐答案
像这样:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = explode("?v=", $link);
$video_id = $video_id[1];
这是通用的解决方案:
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0&lololo";
$video_id = explode("?v=", $link); // For videos like http://www.youtube.com/watch?v=...
if (empty($video_id[1]))
$video_id = explode("/v/", $link); // For videos like http://www.youtube.com/watch/v/..
$video_id = explode("&", $video_id[1]); // Deleting any other params
$video_id = $video_id[0];
或者只是使用这个正则表达式:
Or just use this regex:
(?v=|/v/)([-a-zA-Z0-9]+)
相关文章