views:

303

answers:

2

Ok I am trying to get the users First Name

the form gets their name perfectly fine and posts it into a variable.

Now I am trying to do error checking

else if(!preg_match("/^[\w-]+$/", $firstNameSignup)) {
       $firstNameSignupError = "Your first name cannot contain numbers or symbols, you entered " . $firstNameSignup;
       $firstNameSignup = "";
      }

I tried the above code and it does not like me but my if statement

if(!isset($firstNameSignup) || $firstNameSignup == "") {
   $firstNameSignupError = "You must enter your first name";
  }

works fine so I know that the error is in that else if statement... most likely in my regular expression

any help??? I'm totally at a loss (really new to PHP and regular expressions)

Thanks Shelby

A: 
else if(preg_match('#[^a-z]+$#i', $firstNameSignup)) {
            $firstNameSignupError = "Your first name cannot contain numbers or symbols, you entered " . $firstNameSignup;
            $firstNameSignup = "";
        }

finally found at that the above code worked

MrEnder
That will always work unless there is an error. preg_match always returns true as it returns an int.
Christian
what do u mean?
MrEnder
if statements are conditionals, their test can always only be true or false. preg_match doesn't just return true or false, you need to make it a conditional...by simply doing (preg_match()) it will always return true, whether it matched or not. The only time it will return false is if there is an error (an issue with your regex perhaps.) Read my answer above, you need to see if it matched; (ie if (preg_match() == 1)) Hope that makes sense.
Christian
@Christian - due to PHP being cool, the statement will work as it is supposed to - true on match and false on no match. As you may see here: http://us2.php.net/preg_match . preg_match returns the NUMBER of matches which is either 0 or positive number (false on error of course). Due to PHP's typecasting 0 (zero) will be casted to boolean FALSE and the IF condition will fail (only if no matches occured).
bisko
Bleugh, I didn't even think of that, I was thinking preg_match === FALSE... Which is not what is being done... Der to me. :)
Christian
A: 

Preg match returns FALSE on error.

You need to do like so;

else if(preg_match("/^[\w-]+$/", $firstNameSignup) == 0) { // no matches

http://au2.php.net/preg_match

Christian