Return to Snippet

Revision: 53045
at November 10, 2011 23:27 by ciromiranda


Updated Code
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;
	}		
}

Revision: 53044
at November 10, 2011 23:24 by ciromiranda


Initial Code
public static 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;
		}		
	}

Initial URL


Initial Description
Parses various types of  YouTube URLs returning the embed iframe with optional width and height

Initial Title
Parse YouTube URLS

Initial Tags


Initial Language
PHP