PHP get youtube,vimeo video url from string and check if exist and play

When you are working with php, probably your page includes youtube or vimeo video url in the description.Check that youtube/vimeo video url is valid and that video is exist, then it must be play in the page.So now I’m going to describes how to get only that video url from the description, check that video is exist and how to to play it.

Think this is my description with including video url.

$textDescription = "http://www.youtube.com/watch?v=5sRDHnTApSw&feature=youtu.be The master Bob Haro was putting together a sequence for the Olympic opening that sadly got cut due to time constraints. They made this little film of some of the riders. Nice work BOB, see you at EICMA again!";

Now I want to get that video url.

 $parsed 	= parse_url($textDescription);
 $hostname 	= $parsed['host'];  // www.youtube.com
 $query 	= $parsed['query']; // v=5sRDHnTApSw&feature=youtu.be.......to end of the string

PHP parse_url is parse the url and return its components like http,site url,query strings…etc.

Now get the video ID from string

$Arr = explode('v=',$query);
// from video id, until to end of the string like 5sRDHnTApSw&feature=youtu.be The master Bob Haro......
$videoIDwithString = $Arr[1];
$videoID = substr($videoIDwithString,0,11); // clean video ID

Note:
Always video ID length is 11 characters for youtube video.
The individual characters come from a set of 64 possibilities (A-Za-z0-9_-).
64^11 is somewhat more than 2^64. (10 characters would not be enough.) So basically each youtube ID is actually a 64bit number. And I quite doubt they will ever run out of those.

Now Create the player for YOUTUBE VIDEO

//YOUTUBE.COM
if( (isset($videoID)) && (isset($hostname)) && ($hostname=='www.youtube.com' || $hostname=='youtube.com')){
?>


Create the player for VIMEO VIDEO

//https://vimeo.com/45980982
if((isset($hostname)) && $hostname=='vimeo.com'){
	$ArrV = explode('://vimeo.com/',$path); // from ID to end of the string
	$videoID = substr($ArrV[0],1,8); // to get video ID , always length is 8 characters
	$vimdeoIDInt = intval($videoID); // ID must be integer
	//print_r($vimdeoIDInt);
?>


Put this all together.






Download Source(1.43 KB)