[英]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.
php 代码工作正常,但它也在计算空格。 what should i add in order for the code to not count the white-spaces.
我应该添加什么以使代码不计算空格。 My php code:
我的php代码:
<?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);
?>
No need to reinvent the wheel.无需重新发明轮子。 PHP has a built in function for counting words in a string: str_word_count() .
PHP 有一个用于计算字符串中单词的内置函数: str_word_count() 。
Using it in combination with file_get_contents() to get the file contents, you can make the code way smaller.将它与file_get_contents()结合使用来获取文件内容,可以使代码更小。
This should do what you want:这应该做你想做的:
$wordCount = str_word_count(file_get_contents('trial.txt'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.