SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Now available in Orange Tijmen's Avatar
    Join Date
    Jul 2004
    Location
    The Netherlands
    Posts
    1,472
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    small problem with preg_match for url validation

    Hi,

    I got the following code to check if the submitted url is valid.

    Code:
     if(!preg_match('/(http):\/\/([a-z0-9]+)\.[a-z]{2,4}/i', $_POST['website'])) {
         echo 'wrong';
     } else {
         echo 'oke';
     }
    When i enter

    @$.#$ = wrong
    aa.aa = fine
    aa.a = wrong which makes sense, but when i enter aa.aaaaaa it's also fine. This {2,4} tells it that it needs to be between 2 and 4 characters, if i enter 1 character it comes up with the error, but 5 characters is fine?

    Another thing is this
    aa.aa.com will validate, but aa.aa.c will also validate. Which it shouldn't do, so i try'd this.

    Code:
    if(!preg_match("/(http):\/\/([a-z0-9]*)?\.([a-z0-9-_])+\.([a-z]{2,4})/i", $_POST['website'])) {
    If i understand it correctly it should check the for a-z0-9 after the http:// and then their might be another value after the. And after that you have the .com/.net But it doesn't really work..

    Any idea's how i could fix these problems?

  2. #2
    SitePoint Enthusiast szigeti's Avatar
    Join Date
    May 2005
    Location
    Hungary
    Posts
    70
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:
    PHP Code:
    if (preg_match('#^https?://[a-z0-9-._]+\.[a-z0-9]{2,4}$#i'$_POST['website']))
    {
        echo 
    'OK, that\'s a valid URL';
    }
    else
    {
        echo 
    'invalid URL';

    This {2,4} tells it that it needs to be between 2 and 4 characters, if i enter 1 character it comes up with the error, but 5 characters is fine?
    In that case you should put a $ at the end of the regex, which is an "end of line". (^ means "start of line" by the way). The bug was that it has found 2--4 characters, but you didn't told the regex engine that the URL should end there.

    There's a really useful page about regular expressions here: http://regular-expression.info/
    Eat healthy,
    Exercise daily,
    Die anyway.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •