Regular Expression for a password with at least 8 characters and at least 1 non-alphanumeric character(s)

15,354

Try something like this to check if they used non-alphanumeric characters:

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

The if statement will evaluate to true if the $password does not contain at least one of the characters not in the list (alphanumeric characters).

Share:
15,354
Johnathan Au
Author by

Johnathan Au

Updated on July 27, 2022

Comments

  • Johnathan Au
    Johnathan Au almost 2 years

    I am trying to make a check in PHP if a user changes their password their new password must be 8 or more characters and with at least 1 non-alphanumeric password. How should I check this and what would the regex be?

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

    Thanks