php统计单词频次需先明确定义“单词”:基础版用preg_split('/1+/'匹配非字母数字分割;进阶版用'/[a-za-z]+(?:\'[a-za-z]+)?/'保留缩写;再结合strtolower、array_count_values及停用词过滤提升准确性。a-za-z0-9 ↩

直接用 PHP 统计一段文本中单词出现频次,核心是:分词 → 标准化(小写、去标点)→ 计数。关键不在“统计”,而在“怎么定义一个单词”。
一、基础版:按空格分割 + 小写 + 去标点
适用于英文为主、格式较规整的文本。
- 用 preg_split() 按非字母数字字符切分,比
explode(' ', $text)更可靠 - 过滤空字符串和纯空白项
- 统一转为小写,避免
"Hello"和"hello"被算作两个词 - 用 array_count_values() 快速计数
$text = "Hello, world! Hello PHP. PHP is great, isn't it?";
$words = preg_split('/[^a-zA-Z0-9]+/', strtolower($text), -1, PREG_SPLIT_NO_EMPTY);
$freq = array_count_values($words);
// 结果:['hello'=>2, 'world'=>1, 'php'=>2, 'is'=>1, 'great'=>1, 'isnt'=>1, 'it'=>1]
二、进阶版:保留撇号(如 isn't, don't),但剔除孤立标点
真实英文常含缩写,简单删所有非字母会把 isn't 变成 isnt,丢失语义。
- 改用正则匹配“有效单词”:
/[a-zA-Z]+(?:'[a-zA-Z]+)?/ - 该模式能捕获
don't、it's、PHP,跳过!、,、... - 仍需
strtolower()统一大小写
$words = [];
preg_match_all('/[a-zA-Z]+(?:\'[a-zA-Z]+)?/', strtolower($text), $matches);
if (!empty($matches[0])) {
$words = $matches[0];
}
$freq = array_count_values($words);
三、实用增强:排除停用词 & 限制最小长度
统计结果常被 the、is、a 等高频虚词淹没,可过滤提升可读性。
- 定义停用词数组:
$stopwords = ['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'is', 'are', 'was', 'were']; - 用
array_filter()剔除停用词和长度 - 再调用
array_count_values()
四、输出建议:按频次降序,取前 N 个高频词
原始数组键无序,直接遍历不直观。
- 用 arsort($freq) 按值(频次)降序排列,保持键关联
- 用 array_slice($freq, 0, 10) 取前 10 个高频词
- 打印时可用
foreach输出单词 => 次数
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











