Parse YouTube URLS


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

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


Copy this code and paste it in your HTML
  1. function getEmbedYT($link, $width=430, $height=230){
  2. $final = '<iframe width="'.$width.'" height="'.$height.'" src="http://www.youtube.com/embed/{code}" frameborder="0"></iframe>';
  3.  
  4. //se o link for o embed (altera o width e height)
  5. if(stristr($link, "iframe")){
  6.  
  7. $link = preg_replace("/width=(\")[0-9]+(\")/", 'width="'.$width.'"', $link);
  8. $link = preg_replace("/height=(\")[0-9]+(\")/", 'height="'.$height.'"', $link);
  9.  
  10. return $link;
  11. }
  12.  
  13. $parsed = parse_url($link);
  14.  
  15. //link URL
  16. if(stristr($parsed['path'], 'watch') !== false){
  17. parse_str($parsed['query'], $args);
  18. $code = $args['v'];
  19. }//link do embbed
  20. elseif(stristr($parsed['path'], 'embed') !== false){
  21. $code = str_replace("/embed/", "", $parsed['path']);
  22. }//short link
  23. elseif($parsed['host'] == 'youtu.be'){
  24. $code = str_replace("/", "", $parsed['path']);
  25. }
  26.  
  27. if($code){
  28. $final = str_replace("{code}", $code, $final);
  29.  
  30. return $final;
  31. }else{
  32.  
  33. return null;
  34. }
  35. }

Report this snippet


Comments


You need to login to view comments.