PHP count average word length and characters in a text file
In this post, you will learn how to count the average word length in a file and the average character length in a text file using the PHP programming language. This is important if you want to do something with the file words. Manual calculation is not fruitful if you deal with a large file size. PHP provides various techniques to deal with the file contents.
First, we used the PHP 'fopen()' function to open the file for processing. Then, we used 'feof' to loop till the end of the file. Next, by using 'fgets()', we have processed a line from the file. The 'preg_split()' function is used in this code, which splits a string by a regular expression. The regular express engine's white space metacharacters are used, which include space, tab, newline, and carriage return. We have stored the 'preg_split()' return values in a variable and have a loop over this variable to count the average word length and characters in a text file.
Suppose we have the following text file-
test.txt
In this article, you will learn how to count the average word length in a file
and average character length in a word.
This is important if you want to do something with the file words.
Manual calculation is not fruitful if you will deal with long file size.
PHP provides various techniques to deal with file contents.
PHP count average word length and characters
index.phpHere is the main PHP file 'index.php', that we will call from the browser.
<?php
$wordCount = 0;
$wordLength = 0;
if ($fh = fopen('test.txt','r')) {
while (! feof($fh)) {
if ($s = fgets($fh)) {
$totalWords = preg_split('/\s+/',$s,-1,PREG_SPLIT_NO_EMPTY);
foreach ($totalWords as $word) {
$wordCount++;
$wordLength += strlen($word);
}
}
}
}
print sprintf("The average word length over %d words is %.02f characters.",
$wordCount,
$wordLength/$wordCount);
?>
The above code returns the following output-
The average word length over 58 words is 4.50 characters.
Related Articles
Remove empty values from array PHPRemove duplicates from array PHP
PHP remove last character from string
Remove character from string Python
PHP sanitize input for MySQL
PHP random quote generator
PHP String Contains
PHP calculate percentage of total
PHP Fix: invalid argument supplied for foreach
Locking files with flock()
How to get current directory, filename and code line number in PHP
PHP SplFileObject Standard Library
How to lock a file using PHP
How to upload multiple files and store in MySQL database using PHP
PHP generate doc
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Simple File Upload Script in PHP