Search code examples
phppreg-match

How to get facebook video id by preg_match


My user copy any video URL and paste in my web input form to submit a video. I using php preg_match to get video id from facebook/you-tube/yahoo/vimeo's URL. But every thinks work well without facebook. I cannot get any Facebook video id.

Now a day facebook used different type of url for there video, like:

  1. https://www.facebook.com/nikololok/videos/t.100000216422619/10153335471682286/?type=2

  2. https://www.facebook.com/nikololok/videos/10153335471682286/

  3. https://www.facebook.com/videos/10153335471682286/

Please help me get facebook video ID 10153335471682286 from any of those type url.

my work: (

$y_video = "https://www.youtube.com/watch?v=N1rethmzohw";
$f_video = "https://www.facebook.com/nikololok/videos/t.100000216422619/10153335471682286/?type=2";
$v_video = "https://vimeo.com/groups/imotional/videos/131543976";

//For facebook
if ($f_video > ''){
    if (preg_match("/(?:.*)\/([0-9]*)/i", $f_video, $matches)) {
    print 'facebook: ' . $matches[1] . '<br />';
    }
}
//For youtube
if ($y_video > ''){
    if (preg_match("/(?:.*)v=([a-zA-Z0-9]*)/i", $y_video, $matches)) {
    print 'youtube: ' . $matches[1] . '<br />';
    }
}
//For vimeo
if ($v_video > ''){
    if (preg_match("/(?:.*)\/([0-9]*)/i", $v_video, $matches)) {
    print 'vimeo: ' . $matches[1] . '<br />';
    }
}

Solution

  • Here's my answer:

    <?php
    $videos = array('https://www.facebook.com/nikololok/videos/t.100000216422619/10153335471682286/?type=2', 'https://www.facebook.com/nikololok/videos/10153335471682286/', 'https://www.facebook.com/videos/10153335471682286/);');
    foreach($videos as $f_video){
        preg_match("~/videos/(?:t\.\d+/)?(\d+)~i", $f_video, $matches);
        print_r($matches);
    }
    

    I changed the delimiter to ~ so the /'s in the URL don't need to be escaped.

    Here's the regex101 link, https://regex101.com/r/qN8hK8/1, which will give you a detailed description of what the regex is doing. If you have questions please post.