How to check If preg_match is False instead of True?

I have this code which makes sure that the username is only letters and numbers. But the 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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *