PHP:如何检查URL是Youtube的还是vimeo的

2022-08-30 23:52:50

如何编写一个函数来检查提供的URL是youtube还是vimeo?

例如,我有这两个URL,我将它们作为字符串存储在数据库中,

http://vimeo.com/24456787

http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded

如果URL是youtube,那么我会将URL重写为,

http://www.youtube.com/embed/rj18UQjPpGA?rel=0&wmode=transparent

如果URL是vimeo,那么我会将此URL重写为,

http://vimeo.com/moogaloop.swf?clip_id=24456787

谢谢。


答案 1

使用该函数拆分URL,然后只做你的正常检查parse_url

$url = 'http://www.youtube.com/watch?v=rj18UQjPpGA&feature=player_embedded';
$parsed = parse_url($url);

会给你这个数组

array
  'scheme' => string 'http' (length=4)
  'host' => string 'www.youtube.com' (length=15)
  'path' => string '/watch' (length=6)
  'query' => string 'v=rj18UQjPpGA&feature=player_embedded' (length=37)

答案 2

我最近写了这个函数来做到这一点,希望它对某人有用:

    /**
 * [determineVideoUrlType used to determine what kind of url is being submitted here]
 * @param  string $url either a YouTube or Vimeo URL string
 * @return array will return either "youtube","vimeo" or "none" and also the video id from the url
 */

public function determineVideoUrlType($url) {


    $yt_rx = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/';
    $has_match_youtube = preg_match($yt_rx, $url, $yt_matches);


    $vm_rx = '/(https?:\/\/)?(www\.)?(player\.)?vimeo\.com\/([a-z]*\/)*([‌​0-9]{6,11})[?]?.*/';
    $has_match_vimeo = preg_match($vm_rx, $url, $vm_matches);


    //Then we want the video id which is:
    if($has_match_youtube) {
        $video_id = $yt_matches[5]; 
        $type = 'youtube';
    }
    elseif($has_match_vimeo) {
        $video_id = $vm_matches[5];
        $type = 'vimeo';
    }
    else {
        $video_id = 0;
        $type = 'none';
    }


    $data['video_id'] = $video_id;
    $data['video_type'] = $type;

    return $data;

}

推荐