我想计算文本文件中的单词数。下面是我尝试过的代码。php 代码工作正常,但它也在计算空格。我应该添加什么以使代码不计算空格。我的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);
?>
Run Code Online (Sandbox Code Playgroud)
无需重新发明轮子。PHP 有一个用于计算字符串中单词的内置函数:str_word_count()。
将它与file_get_contents()结合使用来获取文件内容,可以使代码更小。
这应该做你想做的:
$wordCount = str_word_count(file_get_contents('trial.txt'));
Run Code Online (Sandbox Code Playgroud)