Convert youtube-links in text to embedded flash player

If you have a forum, cms or whatever and the users contribute with youtube-links in their posts. You probably convert the urls to a-href links at display time, like this:


If the posted link is a youtube-link, are you converting it the same way? Why should you! A cooler way is to convert the link to a embedded youtube-video, like this:


I have written a small php-function that converts youtube-links (like: in text to embedded videos. Download it, give it a try and feel free to modify it to suit your needs. Feedback is appreciated.

Download parseYoutubeUrls

function parseYoutubeUrls($text, $width = -1, $height = -1)
// defaults
if($width == -1) { $width = 425; }
if($height == -1) { $height = round((344/425) * $width); }

// get all urls in text
$regexp = "/<a\s+.*?href=[\"\']?([^\"\' >]*)[\"\']?[^>]*>(.*)<\/a>/i";
if(preg_match_all($regexp, $text, $matches, PREG_SET_ORDER))
// check each url
foreach($matches as $match)
// replace all youtube urls with embedded flash player
$parsedUrl = parse_url($match[1]);
parse_str($parsedUrl["query"], $query);
$videoId = ($query['v']);
$replace = '<p><object width="'.$width.'" height="'.$height.'"><param name="movie" value="'.$videoId.'&hl=sv&fs=1&rel=0"> </param> <param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'.$videoId.'&hl=sv&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'.$width.'" height="'.$height.'"></embed></object></p>';
$text = str_replace($match[0],$replace, $text);
return $text;

2 reaktioner till “Convert youtube-links in text to embedded flash player”


E-postadressen publiceras inte. Obligatoriska fält är märkta *