Post Thumbnail

How to get youtube video id from URL (Perfect Way). : PHP

Jan022012
3

Hi to all, while working on my one wordpress project, i need some function which can get youtube video ID from it url, so i tried to search ready made function on google.
i tried most of all function which are available online but non of them worked perfectly for me, so i take quick action of writing one new function, and so it take only few minutes and i am done with it, after that i thought to share it with you all so here the code.

<?php
/*
Author : Ayush Singh
Url : Webgarb.com
Get youtube video ID from URL.
*/
 
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],0,12);
  	 return false;
 }
 
 
/* Examples */
echo youtubeID("http://www.youtube.com/watch?v=kffacxfA7G4"). "<br />";
echo youtubeID("http://www.youtube.com/watch?feature=player_detailpage&v=kffacxfA7G4"). "<br />";
echo youtubeID("http://www.youtube.com/watch?feature=player_detailpage&v=kffacxfA7G4#t=25s"). "<br />";
?>

Thanks for reading :).
Enjoy and leave comment if you find this function usefull.

Comments

3 Comment(s) to "How to get youtube video id from URL (Perfect Way). : PHP"

  1. Sugel says:
    January 18, 2012 at 2:30 pm

    how do I add that id in place of the single video id included in the example. I tried just exchanging the playlist id (F8CEAC0509B5784C), with the video id from the example, but was told it was not a valid video id.

     

Leave your words

Oh Cmon Don't Be Shy.
(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">