views:

416

answers:

3

What's the best preg_match syntax to check if a url is a video link of youtube/vimeo/ or dailymotion?

maybe if it's hard, then just to check the domain name.

Thanks

+2  A: 

I wouldn't use preg_match() for this. I think parse_url() is probably a better choice. You can pass a URL string into it, and it will break it down into all the subcomponents for you.

I don't know what the specific video URLs for those sites you mentioned look like, but I'm sure you could come up with some identifying criteria for each one that you could use with the results of parse_url() to identify. As an example, here's what the breakdown of a YouTube link might look like:

$res = parse_url("http://www.youtube.com/watch?v=Sv5iEK-IEzw");
print_r($res);

/* outputs: 
Array (
    [scheme] => http
    [host] => www.youtube.com
    [path] => /watch
    [query] => v=Sv5iEK-IEzw
)
*/

You could probably identify it based on the host name and the path in this case.

zombat
A: 
if (preg_match ("/\b(?:vimeo|youtube|dailymotion)\.com\b/i", $url)) {
   echo "It's a video";
}
mopoke
A: 

I don't know how you get that url, but you might want to check for "watch" instead of just www.youtube.com (since youtube video links usually have the path as watch?something.

$res = parse_url("http://www.youtube.com/watch?v=Sv5iEK-IEzw");
if ( preg_match( "/\/watch/" , $res["path"]  ) ){
    echo "found video\n ";
}
ghostdog74