A regular expression for a password with at least 8 characters and at least 1 non-alphanumeric character (s)

I am trying to check in PHP if the user changes his password, the new password must contain 8 or more characters and at least 1 non-alphanumeric password. How to check this and what will happen to regex?

Checking the length is the easy part strlen >= 8. My problem is regular expressions. I really have no idea about regular expressions even after many years of studying computer science.

thank

+3
source share
6 answers

Try something like this to see if they are using alphanumeric characters:

if( !preg_match( '/[^A-Za-z0-9]+/', $password) || strlen( $password) < 8)
{
    echo "Invalid password!";
}

if true, $password , (- ).

+4

( )

if (preg_match('/^(?=.*[\W])(?=[a-z0-9])[\w\W]{8,}$/i', '123abc!$'))
{
    //error
}

, 8

0

strlen/mb_strlen, -- . ( ), . :

$password = 'asdf123!';

if(mb_strlen($password) >= 8 and preg_match('/[^0-9A-Za-z]/', $password))
{
    // password is valid
}
0

As far as I know, you cannot achieve this because it is a complex scenario of conditions.

What you need to do is to do this in three ways:

$has8characters = (mb_strlen($_REQUEST['password']) >= 8);
$hasAlphaNum = preg_match('b[a-z0-9]+bi', $_REQUEST['password']);
$hasNonAlphaNum = preg_match('b[\!\@#$%\?&\*\(\)_\-\+=]+bi', $_REQUEST['password']);

This has not been verified, but you are pretty close to what you want to achieve with this ...

Good luck.

0
source

Try it.

~^(.*[\W]+.*){8,}$~
  • . * searches for any character 0 or more times
  • [\ W] + matches at least one character without a word
  • {8,} matches a parenthesized value only if the length is 8 or more characters
  • ^ $ matches start and end of line
0
source

It solves. Give it a try!

if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{8,}$/', $pass)) {
  echo "Password does not meet the requirements! It must be alphanumeric and atleast 8 characters long";
}
0
source

All Articles