亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP計算txt文件中的單詞

PHP計算txt文件中的單詞

PHP
慕的地6264312 2022-10-28 16:16:56
我想計算文本文件中的單詞數。下面是我嘗試過的代碼。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);?> 
查看完整描述

1 回答

?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

無需重新發明輪子。PHP 有一個內置函數用于計算字符串中的單詞:str_word_count()

將它與file_get_contents()結合使用來獲取文件內容,您可以使代碼更小。

這應該做你想要的:

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


查看完整回答
反對 回復 2022-10-28
  • 1 回答
  • 0 關注
  • 122 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號