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

后端 未结 8 1787
感情败类
感情败类 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:53

    As others have noted in the comments, this is a quick and dirty solution that does not handle edge cases well. If the url contains "youtube"(example.com/youtube) it will return a false positive. The parse_url() solution mentioned below is a much more robust solution.


    Regular expressions work well for this type of thing, but often strpos or substr are faster performance wise. Check out the PHP documentation for preg_match(). Below the examples there is a note for exactly this thing.

    Here is prototype code:

    function videoType($url) {
        if (strpos($url, 'youtube') > 0) {
            return 'youtube';
        } elseif (strpos($url, 'vimeo') > 0) {
            return 'vimeo';
        } else {
            return 'unknown';
        }
    }
    

    Obviously returning a string isn't the best idea, but you get the point. Substitute your own business logic.

    0 讨论(0)
  • 2021-02-02 02:02

    Since all you want to do is check for the presence of a string, use stripos. If it doesn't have youtube.com or vimeo.com in it, the url is malformed, right? stripos is case insensitive, too.

    if(stripos($url,'youtu')===false){
        //must be vimeo
        } else {
        //is youtube
        }
    
    0 讨论(0)
提交回复
热议问题