Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
760 views
in Technique[技术] by (71.8m points)

url - getting youtube video id the PHP

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

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;

}

How can I deal with URLS that use the ?v version rather than the /v/ version?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Like this:

$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = explode("?v=", $link);
$video_id = $video_id[1];

Here is universal solution:

$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]+)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...