Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check If preg_match is False instead of True?

Tags:

php

preg-match

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';
}
like image 760
user2362601 Avatar asked Sep 20 '13 20:09

user2362601


People also ask

Which of the following call to Preg_match will return false?

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 .

What is the difference between Preg_match and Preg_match_all?

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.

Which of the following call to Preg_match will return true?

The preg_match() function returns true if pattern matches otherwise, it returns false.

What does Preg_match mean?

Definition and Usage The preg_match() function returns whether a match was found in a string.


1 Answers

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.

like image 98
tmh Avatar answered Nov 15 '22 18:11

tmh