Monday, November 22, 2010

How to resize youtube embed video using regular expression ?

When we are creating a web application that let the user insert video embeds coming from YouTube or from Vimeo, or what ever else, there is the problem of the embed size. Most probably they will directly insert the embed code, that they are copied from youtube. This size of object tag (iframe, embed, object) may affect our design. If we are creating a video gallery we need to resize the embed code video into our size. In PHP we can use regular expression to resize the embed code.

Sample Code
<?php
//eg :
$video = "<object width="640" height="385">

<param value="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US" name="movie" />

<param value="true" name="allowFullScreen" />

<param value="always" name="allowscriptaccess" /><embed width="640" height="385" allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" src="http://www.youtube.com/v/bIx5vDn28eE?fs=1&amp;hl=en_US"></embed></object>";


// our prefered size : width="208" height="103"
// regular exression to change the height and width
$pattern = "/height=\"[0-9]*\"/";
$video = preg_replace($pattern, "height='103'", $video);
$pattern = "/width=\"[0-9]*\"/";
$video = preg_replace($pattern, "width='208'", $video);
echo $video;

?>
The above code will resize the embed video into the size we are given.

If we want to add the 'wmode' in the video we can assign that value along with the width parameter.

eg :
$video = preg_replace($pattern, "width='208' wmode='transparent'", $video);

No comments:

Post a Comment