Youtube Embed Rewriting

published on April 6th, 2008 · more from the blog →

So the time may come when you have code for embedding a youtube video into a webpage but need that video to be automagically resized and looping and putting the kettle on for you. Well... here's a snippet of code that just might do that for you!

<?php
// function to adjust a youtube videos settings given the embed code


function youtube_adjust($string,$width=425,$height=355,$autoplay=false,$looping=false){
	// match the url in the embed string


	$pattern = '/name="movie" value[\\s=\'"]+([^"\'>\\s]+)/is';
	preg_match($pattern,$string,$url);
	// split the url to get the different parts
	$result = split('[/&]', $url[0]);
	$id = $result[4];


	// shall i adjust these things?
	$autoplay = $autoplay ? 1 : 0;
	$looping = $looping ? 1 : 0; 


	// insert the new settings into the new format string and return it
	return '<a href="http://www.youtube.com/v/%27.$id.%27&hl=en&autoplay=%27.$autoplay.%27&loop=%27.$looping.%27" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-06839183377036349 visible ontop"></a><a href="http://www.youtube.com/v/%27.$id.%27&hl=en&autoplay=%27.$autoplay.%27&loop=%27.$looping.%27" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-010214352500039581 visible ontop"></a><object height="'.$height.'" width="'.$width.'">
<param name="movie" value="http://www.youtube.com/v/'.$id.'&hl=en&autoplay=1"></param>
<param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'.$id.'&hl=en&autoplay='.$autoplay.'&loop='.$looping.'" type="application/x-shockwave-flash" wmode="transparent" height="'.$height.'" width="'.$width.'"></embed></object>';
}


// this is the string youtube give you
$string = '<a href="http://www.youtube.com/v/iy3T3sp4EW4&hl=en" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-06839183377036349 visible ontop"></a><a href="http://www.youtube.com/v/iy3T3sp4EW4&hl=en" style="left: 0px ! important; top: 22px ! important" title="Click here to block this object with Adblock Plus" class="abp-objtab-010214352500039581 visible ontop"></a><object height="355" width="425">
<param name="movie" value="http://www.youtube.com/v/iy3T3sp4EW4&hl=en"></param>
<param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/iy3T3sp4EW4&hl=en" type="application/x-shockwave-flash" wmode="transparent" height="355" width="425"></embed></object>';


// call and output it yar
echo youtube_adjust($string,200,100,true,true);
?>

P.S Wordpress is gay and likes inserting random character places, sorry if this has screwed up the code above.