PHP File: Counting Characters and Words in File



PHP File Tips - Part 10: With little trick, you can count number of character or word in a file. Read file into string, then use strlen() or str_word_count(). Like this:
<?php
$f = "test.txt";

// read into string
$str = file_get_contents($f);

// count characters
$numChar = strlen($str);
echo "This file have ". $numChar . " character(s)";

// count characters withour spaces
$str2 = ereg_replace('[[:space:]]+', '', $str);
$numChar = strlen($str2);
echo "This file have ". $numChar . " character(s) without spaces";

// count words
$numWords = str_word_count($str);
echo "This file have ". $numWords . " words";

?>


Series this article:
PHP File: 3 Way of Reading File
PHP File: Reading File at Particular Lines
PHP File: Reading File at Particular Byte Ranges
PHP File: Checking File or Directory
PHP File: Showing All File in A Directory
PHP File: Showing All Files and Folders in Particular Directory
PHP File: Retrieving File Statistic
PHP File: Retrieving More File Information
PHP File: Counting Lines in a File
PHP File: Counting Characters and Words in File
PHP File: Writing File
PHP File: Locking and Unlocking File
PHP File: Removing Lines From File
PHP File: Inserting Lines into a File


Tag: file, character, word, count Category: PHP Basic Post : April 14th 2008 Read: 3,245 Bookmark and Share

blog comments powered by Disqus