How to count uppercase, lowercase, special characters, and numeric values using RegEx in PHP

1 Answer

0 votes
function count_characters($text) {
    $uppercase = preg_match_all('/[A-Z]/', $text);
    $lowercase = preg_match_all('/[a-z]/', $text);
    $digits    = preg_match_all('/\d/', $text);
    $special   = preg_match_all('/[^A-Za-z0-9]/', $text);

    return [$uppercase, $lowercase, $digits, $special];
}

$s = "Programming&AI@2026!";

list($u, $l, $d, $spc) = count_characters($s);

echo "Uppercase: $u\n";
echo "Lowercase: $l\n";
echo "Digits: $d\n";
echo "Special characters: $spc\n";



/*
run:

Uppercase: 3
Lowercase: 10
Digits: 4
Special characters: 3

*/

 



answered Feb 20 by avibootz

Related questions

...