views:

52

answers:

2
preg_match_all("/[^A-Za-z0-9]/",$new_password,$out);

The above only checks the 1st character, how to check whether all are alpha-numeric?

+3  A: 
preg_match("/^[A-Za-z0-9]*$/", $new_password);

This gives true if all characters are alphanumeric (but beware of non-english characters). ^ marks the start of the string, and ^$^ marks the end. It also gives true if the string is empty. If you require that the string not be empty, you can use the + quantifier instead of *:

preg_match("/^[A-Za-z0-9]+$/", $new_password);
Artefacto
replace + with * if you allow empty strings
Yanick Rochon
@Yah You're right, I've changed the answer. It's that for an empty string all the characters are alphanumeric (and non-alphanumeric for that matter).
Artefacto
@Artefacto They're Schrödinger strings! :-O
deceze
+4  A: 

It's probably a better idea to use the builtin functions: ctype_alnum

Jani Hartikainen
I'd go with this and avoid the unnecessary overhead of regular expressions.
casablanca
+1 The `ctype` functions are surprisingly under-appreciated. :) @casablanca It's easier to read and understand as well.
deceze
Does it depends on any php extention?
wamp
@wamp http://www.php.net/manual/en/ctype.requirements.php No. The `ctype` functions *can* be disabled at compile time, but that's about as likely as `preg_` functions being disabled.
deceze