Jacob Jacob - 7 months ago 154
PHP Question

PHP Regex Facebook Video ID

I have my facebook urls below (which are all facebook videos) and I want to get its id.


  1. https://mbasic.facebook.com/TrendingInPhilippinesOfficial/videos/1722369168023859/

  2. https://mbasic.facebook.com/story.php?story_fbid=1722369168023859&id=1388211471439632



Output must be:

1. 1388211471439632
2. 1388211471439632


I used this regex to get the ID.

preg_match("~/videos/(?:t\.\d+/)?(\d+)~i", $_GET['url'], $matches);
echo $matches[1];


well it works at
#1
but at
#2
it doesn't work.

Any solution into this?

Answer

I'm guessing you want one regex for both link?

$link1 = "https://mbasic.facebook.com/TrendingInPhilippinesOfficial/videos/1722369168023859/";
$link2 = "https://mbasic.facebook.com/story.php?story_fbid=1722369168023859&id=1388211471439632";
$regex = '/(videos|story_fbid)(\/|=)(\d+)(\/|&)?/';

preg_match($regex, $link1, $matches);
preg_match($regex, $link2, $matches2);

Note the ? at the end of the regex, which will allow to parse it without the trailing / or the &. If you want to only parse the id when there's both, remove the question mark from the regex.

The var_dump of $matches would be:

array(5) {
    [0]=>
        string(24) "videos/1722369168023859/"
    [1]=>
        string(6) "videos"
    [2]=>
        string(1) "/"
    [3]=>
        string(16) "1722369168023859"
    [4]=>
        string(1) "/"
}

And the var_dump of $matches2 would be:

array(5) {
    [0]=>
        string(28) "story_fbid=1722369168023859&"
    [1]=>
        string(10) "story_fbid"
    [2]=>
        string(1) "="
    [3]=>
        string(16) "1722369168023859"
    [4]=>
        string(1) "&"
}
Comments