I'm trying to check a string to make sure it's 7-20 characters in length with at least one numerical character.

This is what i'm using.

$var = 'somenumber';
eregi('^([0-9]+|.){7,20}$', $var)

The problem with this is that numerical character can be absent and this still be true.

Any suggestions on how i'd do this so that the numerical character has to be present in the string.

    (?=.{7,20}$)(\D+\d+|\d+\D+)+$

    Try that, I use preg, but as long as ereg supports look ahead assertions it should work. It will make sure you have to have both letters and numbers, even if it's just one of each.

    PS - you might want to make the \D into \w if you just don't want things like question marks and exclamation marks to be allowed.

      Originally posted by Drakla
      Try that, I use preg, but as long as ereg supports look ahead assertions it should work.

      It doesn't. It doesn't have \d or \D either. That's just two reasons why I don't use ereg.

      Either way, using a regexp to check the length of a string is excessively expensive.

      if(strlen($var)>=7 && strlen($var)<=20 && preg_match('/[0-9]/', $var))
      

        Is there a reason for the forward slash?

          Originally posted by iceman2g
          Is there a reason for the forward slash?

          It's being used to mark the beginning and end of the regexp (look up the PCRE pattern syntax in the manual to see why this is necessary).

            Write a Reply...