getting youtube video id the PHP

2019-02-18 09:51发布

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?

11条回答
叛逆
2楼-- · 2019-02-18 10:25

i just would search for the last "/" or the last "=". After it you find always the video-id.

查看更多
甜甜的少女心
3楼-- · 2019-02-18 10:29

Try:


function youtubeID($url){
     $res = explode("v",$url);
     if(isset($res[1])) {
        $res1 = explode('&',$res[1]);
        if(isset($res1[1])){
            $res[1] = $res1[0];
        }
        $res1 = explode('#',$res[1]);
        if(isset($res1[1])){
            $res[1] = $res1[0];
        }
     }
     return substr($res[1],1,12);
     return false;
 }
$url = "http://www.youtube.com/watch/v/y40ND8kXDlg";
echo youtubeID($url1);

Should work for both

查看更多
劫难
4楼-- · 2019-02-18 10:40
$parts = explode('=', $link);

// $parts[1] will y40ND8kXDlg

This example works only if there's one '=' in the URL. Ever likely to be more?

查看更多
再贱就再见
5楼-- · 2019-02-18 10:42

This may not be in use still, but there might be other people looking for an answer, so, to get a YouTube ID from a URL.

P.S: This works for all types of URL, I've tested it;

Function getYouTubeID($URL){
    $YouTubeCheck = preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data);
    If($YouTubeCheck){
        $VideoID = $Data[1];
    }
    Return $VideoID;
}

Or just use the preg_match function itself;

If(preg_match('![?&]{1}v=([^&]+)!', $URL . '&', $Data)){
        $VideoID = $Data[1];
}

Hope this helps someone :)!

查看更多
小情绪 Triste *
6楼-- · 2019-02-18 10:42
preg_match("#([\w\d\-]){11}#is", 'http://www.youtube.com/watch?v=y40ND8kXDlg', $matches);
echo $matches[1];
查看更多
别忘想泡老子
7楼-- · 2019-02-18 10:42
<?php
$link = "http://www.youtube.com/watch?v=oHg5SJYRHA0";
$video_id = str_replace('http://www.youtube.com/watch?v=', '', $link);
echo $video_id;
?>

Output:
oHg5SJYRHA0

Source

查看更多
登录 后发表回答