defroster Posted August 26, 2010 Share Posted August 26, 2010 How could I from the varying URLs parse only the YouTube video ID? http://www.youtube.com/watch?v=SwrawcORlp0&feature=player_embedded http://www.youtube.com/watch?v=SwrawcORlp0&feature=popular How can I from the URLs above only extract the id into a variable $url SwrawcORlp0 Thanks, df Quote Link to comment Share on other sites More sharing options...
defroster Posted August 26, 2010 Author Share Posted August 26, 2010 Actually just stumbled upon one which works well. /* * Retrieve the video ID from a YouTube video URL * @param $ytURL The full YouTube URL from which the ID will be extracted * @return $ytvID The YouTube video ID string */ function getYTid($ytURL) { $ytvIDlen = 11; // This is the length of YouTube's video IDs // The ID string starts after "v=", which is usually right after // "youtube.com/watch?" in the URL $idStarts = strpos($ytURL, "?v="); // In case the "v=" is NOT right after the "?" (not likely, but I like to keep my // bases covered), it will be after an "&": if($idStarts === FALSE) $idStarts = strpos($ytURL, "&v="); // If still FALSE, URL doesn't have a vid ID if($idStarts === FALSE) die("YouTube video ID not found. Please double-check your URL."); // Offset the start location to match the beginning of the ID string $idStarts +=3; // Get the ID string and return it $ytvID = substr($ytURL, $idStarts, $ytvIDlen); return $ytvID; } Quote Link to comment Share on other sites More sharing options...
afaaro Posted October 29, 2013 Share Posted October 29, 2013 function parse_youtube_url($url,$return='embed',$width='',$height='',$rel=0){ $urls = parse_url($url); //url is http://youtu.be/xxxx if($urls['host'] == 'youtu.be'){ $id = ltrim($urls['path'],'/'); } //url is http://www.youtube.com/embed/xxxx else if(strpos($urls['path'],'embed') == 1){ $id = end(explode('/',$urls['path'])); } //url is xxxx only else if(strpos($url,'/')===false){ $id = $url; } //http://www.youtube.com/watch?feature=player_embedded&v=m-t4pcO99gI //url is http://www.youtube.com/watch?v=xxxx else{ parse_str($urls['query']); $id = $v; if(!empty($feature)){ $id = end(explode('v=',$urls['query'])); } } //return embed iframe if($return == 'embed'){ return '</pre> <iframe src="http://www.youtube.com/embed/'.$id.'?rel='.$rel.'" frameborder="0" width="'.($width?$width:560).'" height="'.($height?$height:349).'"></iframe> <pre>'; } //return normal thumb else if($return == 'thumb'){ return 'http://i1.ytimg.com/vi/'.$id.'/default.jpg'; } //return hqthumb else if($return == 'hqthumb'){ return 'http://i1.ytimg.com/vi/'.$id.'/hqdefault.jpg'; } // else return id else{ return $id; } } Image: echo "<img src='".parse_youtube_url($row['link'],'thumb')."' />"; Embed: echo parse_youtube_url($dbrow['link'],'embed'); Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.