首页 > 解决方案 > 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);
?> 

标签: phphtmlubuntu

解决方案


无需重新发明轮子。PHP 有一个内置函数用于计算字符串中的单词:str_word_count()

将它与file_get_contents()结合使用来获取文件内容,您可以使代码更小。

这应该做你想要的:

$wordCount = str_word_count(file_get_contents('trial.txt'));

推荐阅读