PHP: How to check whether the URL is Youtube's or vimeo's

后端 未结 8 1815
感情败类
感情败类 2021-02-02 01:19

How can I write a function to check whether the provided URLs is youtube or vimeo?

For instance, I have this two URLs that I store in a database as strings,



        
8条回答
  •  北恋
    北恋 (楼主)
    2021-02-02 01:38

    I recently wrote this function to do exactly this, hopefully it's useful to someone:

        /**
     * [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;
    
    }
    

提交回复
热议问题