2

How can I take the YouTube embedded code that YouTube provides and use a regular expression to convert it to valid FBML code, that is, use the fb:swf tag?

So far the regular expression I've come up with is:

preg_replace('/<object(.*)<\/object>/i', "Whatever I need here...", $str);

I know it's lame, but it's my first try.

PS: Sample of the YouTube embedded code,

<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/NWHfY_lvKIQ&hl=en_GB&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/NWHfY_lvKIQ&hl=en_GB&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gaurav Sharma
  • 4,032
  • 14
  • 46
  • 72
  • 1
    What should the result be for the given sample ? – codaddict Mar 10 '10 at 12:27
  • I assume you're asking how to gather the video URL from the embed code and then you do your thing and get whatever you want with it, right ? – Marcelo Mar 10 '10 at 12:31
  • http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – P Daddy Mar 10 '10 at 12:40
  • P Daddy, When talking about the automatically generated youtube embed code, i guess it's safe to say that everything that comes in there is pretty predictable, so there would not be any surprises, making it then possible to parse – Marcelo Mar 10 '10 at 12:51
  • As long as you're ready to make changes whenever youtube does. – P Daddy Mar 10 '10 at 13:21

2 Answers2

0

I had to do this just the other day. Here's a function that I wrote to get the clip id's in a string/input and put them into an array (which you can the insert into your embedded object):

preg_match_all('/\/vi?\/([A-Za-z0-9\+_-]+)/i', $str_containing_yt_ids, $yt_ids);

then

print_r($yt_ids);

and if you need to dynamically get titles:

function get_yt_title($clip_id){
    $feedURL = 'http://gdata.youtube.com/feeds/api/videos/' . $clip_id;
    $entry = simplexml_load_file($feedURL);
    $video= new stdClass;
    $media = $entry->children('http://search.yahoo.com/mrss/');
    $video->title = ucwords(strtolower($media->group->title));
    return $video->title;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Haroldo
  • 36,607
  • 46
  • 127
  • 169
-2

As far as I've figured, you want to gather the video URL from the embedded code and then you do your thing and get whatever you want with it.

Assuming that there would only be two URLs in the whole embedded code (source and value) and that there are no quotes in URL's (at least not YouTube's) the regular expression I'd use to get the URL is:

[^(src=")]http.*[^"]

Explanation: http that isn't precceeded by 'src="' is got until there is a quote.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marcelo
  • 3,371
  • 10
  • 45
  • 76