Preg_match for all special characters, password checking

36,448

Solution 1

This pattern would allow all characters that's not a digit or a-Z.

[^\da-zA-Z]

Regarding the \W it's a negated \w, which is the same as [A-Za-z0-9_]. Thus will \W be all characters that's not an english letter, digit or an underscore.

As I mentioned as a comment this is a great resource for learning regex. And here's a good site to test the regex.

Solution 2

In case you want to match on special characters

preg_match('/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/', $input)

Solution 3

You can use the POSIX character class [[:punct:]] for the 'special' characters:

<?php
$regex = '[[:punct:]]';

if (preg_match('/'.$regex.'/', 'somepas$', $matches)) {
    print_r($matches);
}
?>

gives:

Array
(
    [0] => $
)
Share:
36,448
JeffBaumgardt
Author by

JeffBaumgardt

I like to keep myself interested but alas I am not interested in the answer.

Updated on December 11, 2020

Comments

  • JeffBaumgardt
    JeffBaumgardt over 3 years

    Ok so I am writing a password checker for our password policy which requires 3 of the 4 major classifications. Where I'm having problems with is the special character match.

    Here's what I have thus far:

    private function PasswordRequirements($ComplexityCount) {
        $Count = 0;
        if(preg_match("/\d/", $this->PostedData['password']) > 0) {
            $Count++;
        }
        if(preg_match("/[A-Z]/", $this->PostedData['password']) > 0) {
            $Count++;
        }
        if(preg_match("/[a-z]/", $this->PostedData['password']) > 0) {
            $Count++;
        }
        // This is where I need help
        if(preg_match("/[~`!@#$%^&*()_-+=\[\]{}\|\\:;\"\'<,>.]/", $this->PostedData['password']) > 0) {
            $Count++;
        }
    
        if($Count >= $ComplexityCount) {
            return true;
        } else {
            return false;
        }
    }
    

    So basically what I'm doing is checking the string for each case, numbers, uppercase, lowercase, and special characters. We don't have any restrictions on any special character and I also need unicode characters. Does the \W work in this case or would that also include numbers again? I can't find great documentation on \W so I'm unclear on this part.

    Does anyone know of a easy regexp that would cover all special characters and unicode characters that does not include numbers and letters?

    Anyone is free to use this as I think more than a few people have been looking for this.