Easiest way to check registration for illegal characters

What is the best, fastest and efficient way to check the dedicated field in a registration form for characters such as:


I came up with a solution that is (example):

$password = "M0NEY$$$";
$check = explode($password);

foreach($check as $char) {
   if(!ctype_punct($char)) { continue; }
   $error = "Password must not contain !@#$%^&*() characters.";

Is there a better, and a nicer solution to perform that check?

Thanks in advance.

you could use a RegExp.

Try this:

Thanks, in the end there was no way to DRY it up as I had to hardcode the “_” allowance anyway.

Typically it’s safer (less likely to overlook something) if you check for a white listed set of characters rather than a black listed set of characters. That is, decide which characters are allowed, and check that each character is one of those allowed characters. This should be easy with a regular expression. preg_match(‘/^\w+$/’, $password)

On a side note, if you’re restricting characters in a password, which your original post seems to be doing, then please just don’t do that. Using special characters is one of the rules for good passwords. You would be forbidding that. And there isn’t even any good reason to restrict password characters.