PHP validation/regex for URL

后端 未结 21 2418
青春惊慌失措
青春惊慌失措 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 02:13

    The best URL Regex that worked for me:

    function valid_URL($url){
        return preg_match('%^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@|\d{1,3}(?:\.\d{1,3}){3}|(?:(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)(?:\.(?:[a-z\d\x{00a1}-\x{ffff}]+-?)*[a-z\d\x{00a1}-\x{ffff}]+)*(?:\.[a-z\x{00a1}-\x{ffff}]{2,6}))(?::\d+)?(?:[^\s]*)?$%iu', $url);
    }
    

    Examples:

    valid_URL('https://twitter.com'); // true
    valid_URL('http://twitter.com');  // true
    valid_URL('http://twitter.co');   // true
    valid_URL('http://t.co');         // true
    valid_URL('http://twitter.c');    // false
    valid_URL('htt://twitter.com');   // false
    
    valid_URL('http://example.com/?a=1&b=2&c=3'); // true
    valid_URL('http://127.0.0.1');    // true
    valid_URL('');                    // false
    valid_URL(1);                     // false
    

    Source: http://urlregex.com/

提交回复
热议问题