开发者

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

开发者 https://www.devze.com 2022-12-25 19:45 出处:网络
I have randomly created strings such as H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp What I want to do is get a count of all Caps, lower case, numeric and special characters in each string as

I have randomly created strings such as

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

What I want to do is get a count of all Caps, lower case, numeric and special characters in each string as they are generated.

I 开发者_JAVA百科am looking for an output similar to Caps = 5 Lower = 3 numneric = 6 Special = 4 Fictitious values of course. I have gone through the php string pages using count_char, substr_count etc but cant find what I am looking for.

Thank you


preg_match_all() returns the number of occurences of a match. You'll just need to fill in the regex correlates for each bit of info you want. For example:

   $s = "Hello World"; 
   preg_match_all('/[A-Z]/', $s, $match);
   $total_ucase = count($match[0]);
   echo "Total uppercase chars: " . $total_ucase; // Total uppercase chars: 2


You can use the 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's 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)
}
0

精彩评论

暂无评论...
验证码 换一张
取 消