PHP – Parse YouTube URLS

The given PHP example parses the various types of YouTube URLs and returning the embed iframe 
with optional width and height.

Code Example:
<?php 
function getEmbedYT($link, $width=430, $height=230){
	$final = '<iframe width="'.$width.'" height="'.$height.'" src="http://www.youtube.com/embed/{code}" frameborder="0"></iframe>';

	//se o link for o embed (altera o width e height)
	if(stristr($link, "iframe")){
		
		$link = preg_replace("/width=(\")[0-9]+(\")/", 'width="'.$width.'"', $link);
		$link = preg_replace("/height=(\")[0-9]+(\")/", 'height="'.$height.'"', $link);
		
		return $link;
	}

	$parsed = parse_url($link);
	
	//link URL
	if(stristr($parsed['path'], 'watch') !== false){
		parse_str($parsed['query'], $args);
		$code = $args['v'];
	}//link do embbed
	elseif(stristr($parsed['path'], 'embed') !== false){
		$code = str_replace("/embed/", "", $parsed['path']);
	}//short link
	elseif($parsed['host'] == 'youtu.be'){
		$code = str_replace("/", "", $parsed['path']);
	}
	
	if($code){
		$final = str_replace("{code}", $code, $final);
		
		return $final;
	}else{
		
		return null;
	}		
}
?>

Post to Twitter Post to Digg Post to Facebook Post to Google Buzz Send Gmail

Leave a Comment

Your email address will not be published. Required fields are marked *