checking a password for upper lower numbers and symbols

18,235

Solution 1

your desired regex is below

   $pattern = ' ^.*(?=.{7,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$ ';
   preg_match($pattern,$password);

DEMO

Solution 2

Either you determine a list of valid symbols:

preg_match('`[\$\*\.,+\[email protected]]`',$password)

or you can look for anything that isn't alnum:

preg_match('`[^0-9a-zA-Z]`',$password)
Share:
18,235
ian
Author by

ian

Updated on June 05, 2022

Comments

  • ian
    ian 4 months

    I am using the below script to check my passwords for length, uppercase, lowercase and numbers.

    How could I change it to make it check FOR symbols instead of against symbols?

    <?php
        $password = 'afsd323A';
        if( 
            //I want to change this first line so that I am also checking for at least 1 symbol.
                ctype_alnum($password) // numbers & digits only 
            && strlen($password)>6 // at least 7 chars 
            && strlen($password)<21 // at most 20 chars 
            && preg_match('`[A-Z]`',$password) // at least one upper case 
            && preg_match('`[a-z]`',$password) // at least one lower case 
            && preg_match('`[0-9]`',$password) // at least one digit 
            )
        { 
            echo 'valid';
        }
        else
        { 
            echo 'not valid';// not valid 
        }     
    ?> 
    
  • Craig White over 11 years
    To check if it contains non-alphanumeric characters try this regular expressions: if(preg_match('/[^a-zA-Z0-9]/', $password) echo('Password contains non-alphanumeric characters');
  • Jacob
    Jacob over 11 years
    Except that OP wants the password to contain at least one of each. At least one upper, one lower, one digit, and one symbol.
  • diEcho
    diEcho over 11 years
    Please try to google... here it is Reference
  • Dmitrij Golubev over 11 years
    I optimized a bit ((?=.*[A-Z])(?=.*[a-z])(?=.*\d).{7,21}) - 27 steps ; your - in 50 steps;
  • diEcho
    diEcho over 11 years
    @Dmitrij how do u find the steps?? any website?? please refer
  • Dmitrij Golubev over 11 years
    I am using RegexBuddy (powerfull and chip tool). Example of debugging you can find here
  • Nico Haase
    Nico Haase 10 months
    Please add some explanation to your answer such that others can learn from it