tags:

views:

47

answers:

3
if(!preg_match("/[a-zA-Z'-]/",$First)) { die ("invalid first name");}

the above only flags input as invalid when the field is all numeric. combinations of letters and numbers pass ok. Some help here for a newby please. thanks.

+3  A: 

Try:

if(!preg_match("/^[a-zA-Z'-]+$/",$First)) { die ("invalid first name");} 

The ^ matches the beginning of the string, the $ matches the end of the string and + after a character group means "one or more" matching characters.

Andy E
Thanks for the fix and the clear explanation!
Bill
+2  A: 

You're only matching a single character. You need to add a wildcard like + (1 or more). Also you're matching anywhere in the string. You need to add anchors (^ for start of string, $ for end of string) to make sure there are no invalid characters.

if (!preg_match("/^[a-zA-Z'-]+$/", $First)) { die ("invalid first name");}

Alternatively you can look for a non-matching character:

if (preg_match("/[^a-zA-Z'-]/", $First)) { die ("invalid first name");}

The ^ inside the square brackets here means "any character that is NOT one of these".

cletus
This would still flag OK for `123abc456`. *EDIT* now it's right :-)
Andy E
+1  A: 

In this case better to look for invalid characters than to try and match all of the characters, once a single invalid character appears, the search can quit and return failure. This is more efficient than always scanning the whole string.

if (preg_match("/[^A-Za-z'-]/", $First)) { die ("invalid first name"); }

the ^ inside the set [] makes it match everything not in the set. and since the string is invalid if we have even one invalid character, there is no need for the set to have a repetition operator.

Even better would be a more helpful error message

if (preg_match("/[^A-Za-z'-]/", $First, $Inv)) { die ("{$Inv[0]} not allowed in first name"); }
John Knoeller
Not to be rude, but why are you even *mentioning* efficiency in this context? You'd have to use the profiling equivalent of the Large Hadron Collider to measure the performance differential between these two approaches. :P
Alan Moore
@Alan: it's never harmful to _know_ which of a set of choices is more efficient, although in this case, the overhead of choosing php probably does swamp out the differences.
John Knoeller