PHP validation/regex for URL

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

    Edit:
    As incidence pointed out this code has been DEPRECATED with the release of PHP 5.3.0 (2009-06-30) and should be used accordingly.


    Just my two cents but I've developed this function and have been using it for a while with success. It's well documented and separated so you can easily change it.

    // Checks if string is a URL
    // @param string $url
    // @return bool
    function isURL($url = NULL) {
        if($url==NULL) return false;
    
        $protocol = '(http://|https://)';
        $allowed = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
    
        $regex = "^". $protocol . // must include the protocol
                 '(' . $allowed . '{1,63}\.)+'. // 1 or several sub domains with a max of 63 chars
                 '[a-z]' . '{2,6}'; // followed by a TLD
        if(eregi($regex, $url)==true) return true;
        else return false;
    }
    

提交回复
热议问题