Search code examples
phphtmlpreg-replacepreg-match

Get youtube/vimeo id with pregmatch


How can I get the video ID for youtube and vimeo videos embed code? A youtube video embed code looks like this:

<iframe width="560" height="315" src="http://www.youtube.com/embed/dbPmWbqAJPs" frameborder="0" allowfullscreen></iframe>

where the ID in this is dbPmWbqAJPs.

A vimeo embed code looks like this:

<iframe src="http://player.vimeo.com/video/62468031?color=00ff00" width="500" height="281" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>

where the ID in this example is 62468031.

I don't want to replace those exact ids, but rather have a pregmatch/pregreplace that finds the id in any embed of vimeo and of youtube.


Solution

  • try this

    vimeo

    $string='<iframe src="http://player.vimeo.com/video/62468031?color=00ff00" width="500" height="281" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>';
    preg_match_all( '~http://player.vimeo.com/video/(.*?)\?~si',$string,$M);
    echo ($M[1][0]);
    

    youtube :

    $string='<iframe width="560" height="315" src="http://www.youtube.com/embed/dbPmWbqAJPs" frameborder="0" allowfullscreen></iframe>';
    preg_match_all( '~http://www.youtube.com/embed/(.*?)\"~si',$string,$M);
    echo ($M[1][0]);