Php 字符串问题。如何计算A、A、数字和特殊字符的数量
我随机创建了字符串,例如Php 字符串问题。如何计算A、A、数字和特殊字符的数量,php,Php,我随机创建了字符串,例如 H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp 我要做的是,在生成每个字符串时,获取每个字符串中所有大写、小写、数字和特殊字符的计数 我正在寻找一个类似的输出 上限=5 下限=3 numeric=6 特殊=4 当然是虚构的价值观。 我用count\u char、substr\u count等浏览了php字符串页面,但找不到我要找的内容 谢谢preg\u match\u all()返回匹配的出现次数。您只需为所需的每一位
H*P2[-%-3:5RW0j*;k52vedsSQ5{)ROkb]P/*DZTr*-UX4sp
我要做的是,在生成每个字符串时,获取每个字符串中所有大写、小写、数字和特殊字符的计数
我正在寻找一个类似的输出
上限=5
下限=3
numeric=6
特殊=4
当然是虚构的价值观。
我用count\u char、substr\u count等浏览了php字符串页面,但找不到我要找的内容
谢谢preg\u match\u all()返回匹配的出现次数。您只需为所需的每一位信息填写正则表达式相关项。例如:
$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
你可以使用
非常感谢rkulla,这使它非常简单。我从未使用过ctype函数。我有另一个地方,这将完美地工作。我会仔细阅读的,非常感谢
$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)
}