PHP validation/regex for URL

后端 未结 21 2101
青春惊慌失措
青春惊慌失措 2020-11-22 01:19

I\'ve been looking for a simple regex for URLs, does anybody have one handy that works well? I didn\'t find one with the zend framework validation classes and have seen sev

21条回答
  •  無奈伤痛
    2020-11-22 01:56

    OK, so this is a little bit more complex then a simple regex, but it allows for different types of urls.

    Examples:

    • google.com
    • www.microsoft.com/
    • http://www.yahoo.com/
    • https://www.bandcamp.com/artist/#!someone-special!

    All which should be marked as valid.

    function is_valid_url($url) {
        // First check: is the url just a domain name? (allow a slash at the end)
        $_domain_regex = "|^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})/?$|";
        if (preg_match($_domain_regex, $url)) {
            return true;
        }
    
        // Second: Check if it's a url with a scheme and all
        $_regex = '#^([a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))$#';
        if (preg_match($_regex, $url, $matches)) {
            // pull out the domain name, and make sure that the domain is valid.
            $_parts = parse_url($url);
            if (!in_array($_parts['scheme'], array( 'http', 'https' )))
                return false;
    
            // Check the domain using the regex, stops domains like "-example.com" passing through
            if (!preg_match($_domain_regex, $_parts['host']))
                return false;
    
            // This domain looks pretty valid. Only way to check it now is to download it!
            return true;
        }
    
        return false;
    }
    

    Note that there is a in_array check for the protocols that you want to allow (currently only http and https are in that list).

    var_dump(is_valid_url('google.com'));         // true
    var_dump(is_valid_url('google.com/'));        // true
    var_dump(is_valid_url('http://google.com'));  // true
    var_dump(is_valid_url('http://google.com/')); // true
    var_dump(is_valid_url('https://google.com')); // true
    

提交回复
热议问题