PHP validation/regex for URL

后端 未结 21 2430
青春惊慌失措
青春惊慌失措 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条回答
  •  萌比男神i
    2020-11-22 02:08

    Peter's Regex doesn't look right to me for many reasons. It allows all kinds of special characters in the domain name and doesn't test for much.

    Frankie's function looks good to me and you can build a good regex from the components if you don't want a function, like so:

    ^(http://|https://)(([a-z0-9]([-a-z0-9]*[a-z0-9]+)?){1,63}\.)+[a-z]{2,6}
    

    Untested but I think that should work.

    Also, Owen's answer doesn't look 100% either. I took the domain part of the regex and tested it on a Regex tester tool http://erik.eae.net/playground/regexp/regexp.html

    I put the following line:

    (\S*?\.\S*?)
    

    in the "regexp" section and the following line:

    -hello.com

    under the "sample text" section.

    The result allowed the minus character through. Because \S means any non-space character.

    Note the regex from Frankie handles the minus because it has this part for the first character:

    [a-z0-9]
    

    Which won't allow the minus or any other special character.

提交回复
热议问题