我希望得到一些以" /" 如下所示。我想要所有" A /"在该阵列中占有一席之地。
choice()
答案 0 :(得分:3)
简单易行..这是您的解决方案: -
$input = preg_quote('A/', '~'); // don't forget to quote input string!
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$result = preg_grep('~' . $input . '~', $arr_vals);
echo count($result); die;
答案 1 :(得分:3)
array_reduce
可用于获取整个数组并计算结果。我们可以使用regular expressions来定义您的模式。结合这两件事,我们有你的解决方案:
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
function match($carry, $item) {
return $carry + preg_match('/A\/./', $item);
}
var_dump(array_reduce($arr_vals, 'match', 0)); // Returns 4
答案 2 :(得分:1)
使用fnmatch
也可以使用shell通配符,例如?
和function count_pattern(array $input, string $pattern): int {
$count = 0;
foreach ($input as $string) {
$count += fnmatch($pattern, $string);
}
return $count;
}
:
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
echo count_pattern($arr_vals, "A/*"); // 4
<强>用法强>
{{1}}
注意:为了使用标量类型提示和返回,您需要PHP7。如果你还没有使用PHP7,你可以省略它们。
答案 3 :(得分:0)
是的正确答案是
$input = preg_quote('A/', '~'); // don't forget to quote input string!
$arr_vals = array("A/V","A/B","B/A","D/D","A/v","A/A");
$result = preg_grep('~' . $input . '~', $arr_vals);
echo count($result); die;