I'm really having some difficult wrapping my head around regex and preg_replace. What I want to do is have a function that scans an entire page for any <a href> tags pointing to Youtube and then convert them into an embedded youtube video.
Here's a code to show kinda of what I mean:
<?php
$youtubelink = "http://www.youtube.com/watch?v=Ysl6NCoshk8";
$vid_section = substr( $youtubelink, strpos($youtubelink, '?') + 1, 1 );
$vid_id = substr( $youtubelink, strpos($youtubelink, '=') + 1 );
$embed_code = '<object width="560" height="340"><param name="movie" value="http://www.youtube.com/'.$vid_section.'/'.$vid_id.'&hl=en&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/'.$vid_section.'/'.$vid_id.'&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object>';
echo $embed_code;
?>
First of all I don't want to be providing the link, I want the function to search for it itself. So here's my stab at regex and preg_replace:
echo preg_replace('#(?:<\>]+href=\")?(?:http://)?((?:[a-zA-Z]{1,4}\.)?youtube.com/(?:watch)?\?v=(.{11}?))[^"]*(?:\"[^\<\>]*>)?([^\<\>]*)(?:)?#', '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/'.$matches[2].'"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'.$matches[2].'" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>', $ENTIREPAGE?);
Any idea where I'm going wrong?
To give a little more insight (if your bored enough to care), I have a tumblr blog that posts my twitter RSS feed updates. I sometimes post youtube links and would like them to show up as embedded videos for users to watch on the tumblr page.
Cheers.