Jan
02
2012

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

Post in PHP by Ayush Singh @ 3 Comments | Permalink

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.

Discussion 3 Comments

Says:
January 2, 2012 @ 5:44 pm

Cool!

Says:
January 18, 2012 @ 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.

Says:
January 21, 2012 @ 3:47 am

@sugel : this function only get youtube video ID from url not playlist ID .

Add a Comment

   
My Mood Status
Mood : Moody
Thinking of writing one new plugin for wordpress.
idea is also there just need to start. if you guys have any idea share with me :).
Latest Comments
Recent Comments
Get in Touch