You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用substr_count统计数组中精确匹配内容的问题

解决方案

你的核心问题是误用了substr_count函数——它是用来统计子串在单个字符串中的出现次数,而非匹配数组中的完整元素。要实现数组元素的精确匹配计数,有两种简单可靠的方法:

方法1:使用array_count_values(推荐)

这个函数会直接统计数组中每个元素的出现次数,效率高且代码简洁:

$name = 'apple';
$words = array("apple", "apple juice", "hot apple pie");

// 生成元素出现次数的关联数组
$element_counts = array_count_values($words);
// 取目标元素的计数,不存在则返回0
$ingredient_count = isset($element_counts[$name]) ? $element_counts[$name] : 0;

echo $ingredient_count; // 输出1

当你设置$name = 'apple juice';时,同样会返回1,完全符合预期。

方法2:使用array_filter + count

如果需要更灵活的匹配逻辑(比如后续要扩展匹配规则),可以用过滤函数筛选出完全匹配的元素,再统计数量:

$name = 'apple juice';
$words = array("apple", "apple juice", "hot apple pie");

// 筛选出与目标值严格相等的元素
$matched_items = array_filter($words, function($item) use ($name) {
    return $item === $name; // 严格相等确保精确匹配,包括类型和内容
});

$ingredient_count = count($matched_items);
echo $ingredient_count; // 输出1

为什么原代码结果不符合预期?

你传入substr_count的第一个参数是数组,PHP会自动将数组转换为字符串"Array",但你的结果是3,说明实际代码中可能误将数组拼接成了单个字符串(比如用implode),此时substr_count会统计所有包含目标子串的片段,而非完整元素,所以得到了错误的计数。

内容的提问来源于stack exchange,提问作者Mystic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:45:36