String question. How to count the number of A, a, numeric and special char

I accidentally created lines like

H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp 

What I want to do is get the number of all Caps, lowercase, numeric, and special characters in each line as they are created.

I am looking for a way that looks like Caps = 5 Bottom = 3 numneric = 6 Special = 4 Of course, fictitious values. I looked at the php string pages using count_char, substr_count etc., but can't find what I'm looking for.

thanks

+4
source share
2 answers

preg_match_all () returns the number of matches. You just need to fill out the correlate regular expression for each bit of information you want. For instance:

  $s = "Hello World"; preg_match_all('/[AZ]/', $s, $match); $total_ucase = count($match[0]); echo "Total uppercase chars: " . $total_ucase; // Total uppercase chars: 2 
+5
source

You can use ctype-functions

 $s = 'H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp'; var_dump(foo($s)); function foo($s) { $result = array( 'digit'=>0, 'lower'=>0, 'upper'=>0, 'punct'=>0, 'others'=>0); for($i=0; $i<strlen($s); $i++) { // since this creates a new string consisting only of the character at position $i // it probably not the fastest solution there is. $c = $s[$i]; if ( ctype_digit($c) ) { $result['digit'] += 1; } else if ( ctype_lower($c) ) { $result['lower'] += 1; } else if ( ctype_upper($c) ) { $result['upper'] += 1; } else if ( ctype_punct($c) ) { $result['punct'] += 1; } else { $result['others'] += 1; } } return $result; } 

prints

 array(5) { ["digit"]=> int(8) ["lower"]=> int(11) ["upper"]=> int(14) ["punct"]=> int(15) ["others"]=> int(0) } 
+1
source

Source: https://habr.com/ru/post/1305951/


All Articles