Php Function to resize video from YouTube and Vimeo


/ Published in: PHP
Save to your folder(s)

I’ve made this function that receive the input $video string that contains the dirty embed code as it is from youtube. The second parameter $new_width (if specified) permits to resize the embed code proportionally to the width you need for your template. This function removes also unwanted tags added after the important tag (such as happens from Vimeo embeds that have a p tag after the iframe).


Copy this code and paste it in your HTML
  1. function resizeEmbed($video,$new_width='') {
  2. $video = real_strip_tags($video,array('iframe','embed','param','object'),true);
  3. preg_match("/width=\"([^\"]*)\"/i",$video,$w); $w = (integer)$w[1];
  4. preg_match("/height=\"([^\"]*)\"/i",$video,$h); $h = (integer)$h[1];
  5. if (!$new_width) $new_width = $w;
  6. $w2 = $new_width;
  7. $ratio = (float)($w2/$w);
  8. $h2 = (integer)($h * $ratio);
  9. $video = str_replace("width=\"$w\"","width=\"$w2\"",$video);
  10. $video = str_replace("height=\"$h\"","height=\"$h2\"",$video);
  11. return array("embed"=>$video,"w"=>$w2,"h"=>$h2,"w0"=>$w,"h0"=>$h);
  12. }
  13.  
  14. function real_strip_tags($i_html, $i_allowedtags = array(), $i_trimtext = FALSE) {
  15. if (!is_array($i_allowedtags)) $i_allowedtags = !empty($i_allowedtags) ? array($i_allowedtags) : array();
  16. $tags = implode('|', $i_allowedtags);
  17. if (empty($tags)) $tags = '[a-z]+';
  18. preg_match_all('@</?\s*(' . $tags . ')(\s+[a-z_]+=(\'[^\']+\'|"[^"]+"))*\s*/?>@i', $i_html, $matches);
  19. $full_tags = $matches[0];
  20. $tag_names = $matches[1];
  21. foreach ($full_tags as $i => $full_tag) {
  22. if (!in_array($tag_names[$i], $i_allowedtags)) if ($i_trimtext) unset($full_tags[$i]); else $i_html = str_replace($full_tag, '', $i_html);
  23. }
  24. return $i_trimtext ? implode('', $full_tags) : $i_html;
  25. }

URL: http://www.barattalo.it/2010/10/06/php-function-embed-video-youtube-vimeo/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.