Here is a simple function that will do this for you:
function convert_videos($string) { $rules = array( '#http://(www\.)?youtube\.com/watch\?v=([^ &\n]+)(&.*?(\n|\s))?#i' => '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/$2"></param><embed src="http://www.youtube.com/v/$2" type="application/x-shockwave-flash" width="425" height="350"></embed></object>', '#http://(www\.)?vimeo\.com/([^ ?\n/]+)((\?|/).*?(\n|\s))?#i' => '<object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=$2&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=$2&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object>' ); foreach ($rules as $link => $player) $string = preg_replace($link, $player, $string); return $string; }
Use it simply like this:
echo convert_videos($the_string_that_might_contain_the_link);
I hope this helps someone
I'm the co-founder of
Do you have similar function for Vimeo too?
Comment
Thank you for the Vimeo update
Comment
Thank you for your function….works very well
1 small issue is “&feature=youtube_gdata” shows up underneath player…how could I strip this for cleaner appearance?
Thanks again!
Comment
Qualitypro, can you please post the string (or at least the part with the YouTube URL) here so I can test it and fix this function?
Thanks!
Comment
Simple and awesome. Was about to write something similar but thought I’d check first to see if it had been well done, and it has
Comment
Benj: I think a good programmer always does what you did, this way you can focus on more high level stuff…
Comment
Really nice!
Comment
I have the same problem like Qualitypro.
How to remove the rest part of the link after v=wT-4nESh-4Y?
For example the link is:
http://www.youtube.com/watch?v=wT-4nESh-4Y&feature=relmfu
after converting i still have the end &feature=relmfu
<iframe width=”470″ height=”300″ src=”http://www.youtube.com/embed/wT-4nESh-4Y” frameborder=”0″ allowfullscreen></iframe>&feature=relmfu
Would be great if you could fix that.
Thanks in advance.
Comment
thanks for this script
Comment
I did a little modification to the youtube regex so it solves the “other params” issue
function convert_videos($string) {
$rules = array(
‘#http://(www\.)?youtube\.com/watch\?v=([^ &\n]+)(&.*?(\n|\s))?.+#i’ => ”,
‘#http://(www\.)?vimeo\.com/([^ ?\n/]+)((\?|/).*?(\n|\s))?#i’ => ”
);
foreach ($rules as $link => $player)
$string = preg_replace($link, $player, $string);
return $string;
}
Comment