代码之家  ›  专栏  ›  技术社区  ›  Brad

字符串问题。如何计算a、a、数字和特殊字符的数目

php
  •  4
  • Brad  · 技术社区  · 15 年前

    我随机创建了字符串,例如

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

    我要做的是获取每个字符串中生成的所有大写、小写、数字和特殊字符的计数。

    我正在寻找一个类似 大写=5 下=3 数字=6 特殊=4 当然是虚构的价值观。 我已经使用count_char、substr_count等浏览了php字符串页,但找不到我要查找的内容。

    谢谢你

    2 回复  |  直到 15 年前
        1
  •  5
  •   rkulla    15 年前

    preg_match_all()返回匹配的出现次数。您只需要为您想要的每一个信息位填写regex关联。例如:

       $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
    
        2
  •  1
  •   VolkerK    15 年前

    您可以使用 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;
    }
    

    印刷品

    array(5) {
      ["digit"]=>
      int(8)
      ["lower"]=>
      int(11)
      ["upper"]=>
      int(14)
      ["punct"]=>
      int(15)
      ["others"]=>
      int(0)
    }
    
    推荐文章