php - PHP to count words from a txt file
问题描述
i want to count the number of words in a text file. below is my code i have tried. The php code works fine but it is also counting the white spaces. what should i add in order for the code to not count the white-spaces. My php code:
<?php
$count = 0;
//Opens a file in read mode
$file = fopen("trial.txt", "r");
//Gets each line till end of file is reached
while (($line = fgets($file)) !== false) {
//Splits each line into words
$words = explode(" ", $line);
//Counts each word
$count = $count + count($words);
}
print("Number of words : " . $count);
fclose($file);
?>
解决方案
无需重新发明轮子。PHP 有一个内置函数用于计算字符串中的单词:str_word_count()。
将它与file_get_contents()结合使用来获取文件内容,您可以使代码更小。
这应该做你想要的:
$wordCount = str_word_count(file_get_contents('trial.txt'));
推荐阅读
- python - 调整带/不带颜色条的图形形状
- java - 为什么 java.awt.Button 要求布尔值?
- mysql - 尝试为我的 Python 3.7/Django 项目构建 Docker 映像时出现“OSError:mysql_config not found”
- python - 从用户输入变量向 Python 字典添加信息
- java - 在 Linux 上下载 Java jdk
- jenkins - 如何使用 Jenkins Groovy 脚本设置多个环境变量
- swift - 在 macOS 桌面应用程序中嵌入 Racket 静态库(Xcode 项目)
- facebook - Facebook Inbox Custom Label API 无法搜索我设置的标签
- reactjs - 在反应中动态地将图像添加到 DOM
- javascript - 三.js node.applyMatrix4 不是函数