如何从一组单词中获取特定字母的计数

时间:2017-11-14 06:09:09

标签: php arrays string count

我希望得到一些以" /"  如下所示。我想要所有" A /"在该阵列中占有一席之地。

choice()

4 个答案:

答案 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;