Devstar
Devstar

Reputation: 305

How to return the host name of the video from a URL using regex in php?

There are two urls:

1- http://www.facebook.com/?v=107084586333124'

2- https://www.youtube.com/watch?v=Ws_RjMYE85o

As you can see, both links contains the ?v=..............

Im using a function to retrieve the video ID and the name of the host (youtube, facebook, etc).

Im using this function to get both id and host name

function get_video_id($url){
    $video_id = "";
    //YOUTUBE
    if(preg_match('#(?<=(?:v|i)=)[a-zA-Z0-9-]+(?=&)|(?<=(?:v|i)\/)[^&\n]+|(?<=embed\/)[^"&\n]+|(?<=(?:v|i)=)[^&\n]+|(?<=youtu.be\/)[^&\n]+#', $url, $videoid)){
            if(strlen($videoid[0])) { 
                $video_id = 'youtube:_:'.$videoid[0]; 
            }
    }

    //VIMEO
    if(preg_match('#(https?://)?(www.)?(player.)?vimeo.com/([a-z]*/)*([0-9]{6,11})[?]?.*#', $url, $videoid)){
            if(strlen($videoid[5])) { 
                $video_id = 'vimeo:_:'.$videoid[5]; 
            }
    }

    // Facebook 
    if(preg_match("~/videos/(?:t\.\d+/)?(\d+)~i", $url, $videoid)){
        if(strlen($videoid[0])) { 
            $video_id = 'facebook:_:'.$videoid[1]; 
        }
    }

    return $video_id;


}
    $exp = explode(':_:',get_video_id($_POST['video_url']));
    echo $exp[0] .'=>'.$exp[1];

$exp[0] should return the host name (youtube, vimeo, facebook ....etc);

and $exp[1] return the video id.

The function is working fine but the problem I encounter is that when I submit a facebook video link which contains the ?v=

(eg. http://www.facebook.com/?v=107084586333124')

it always returns youtube as a host name. unlike when I submit a link like this one:

https://www.facebook.com/LadBlab/videos/540736926073557/

it return facebook and thus working fine.

How to check if the url is a facebook video or not when a user submit a link like this one and not confuse it with youtube?

http://www.facebook.com/?v=107084586333124'

Upvotes: 0

Views: 130

Answers (1)

Mubashar Abbas
Mubashar Abbas

Reputation: 5673

You can use something like this

$url = 'http://facebook.com/?v=4654654';
if(strpos($url, 'facebook') != FALSE) {
  //facebook link
} else if(strpos($url, 'youtube') != FALSE) {
  //youtubelink
} else {
  //someother link
}

And then apply your preg_match to each link separately to get the video id.

Upvotes: 1

Related Questions