Check If Preg Match False instead of True

user2362601 picture user2362601 · Sep 20, 2013 · Viewed 65k times · Source

I have this code that makes sure the username is only letters and numbers but then way my code is set up I need it to check if the preg_match is false. Right now it says "if secure echo this" I need it's logic to say "if not secure say this". Can someone help me out?

if (preg_match('/[A-Z]+[a-z]+[0-9]+/', $username))
{
    echo 'Secure enough';
}

Answer

tmh picture tmh · Sep 20, 2013

You can negate the condition like this:

if (!preg_match('/^[A-Za-z0-9]+$/', $username))
{
    echo 'Not secure enough';
}

Also, your regex needs to be [A-Za-z0-9]+ if you mean "alphanumeric" (only letters and numbers) as a whole.

The regex in your code would match if the username 1) starts with a capital letter (or more than one) 2) is followed by one or more lower-case letter and 3) ends with one or more number(s).

Edit:

I'm really not sure if this is what you want. You can do, basically:

if (preg_match('/^[A-Za-z0-9]+$/', $username)) {
    echo 'Is only letters and numbers';
} else {
    echo 'Contains some other characters';
}

Do you want to make sure the string contains special characters so that it will be "secure enough"? Or do you want to make sure that it does not contains special characters, so there won't be any problems processing special characters at some point?

A secure password would be one with special characters and while you probably don't want to enforce this (depending on your target audience), you'd usually want your system to support special characters in passwords.