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 result of preg_match is false
.
Right now it says "if secure echo this". I need its logic to say "if not secure say this". How can I do it?
if (preg_match('/[A-Z]+[a-z]+[0-9]+/', $username))
{
echo 'Secure enough';
}
preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .
preg_match stops looking after the first match. preg_match_all , on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.
The preg_match() function returns true if pattern matches otherwise, it returns false.
Definition and Usage The preg_match() function returns whether a match was found in a string.
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).
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';
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With