Saturday 1 September 2012

PHP: Counting Characters and Words in a File

0 comments


<?php
$file = "test.txt";

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

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

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

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

?>



This is how the output looks:




When 'test.txt' is:







Leave a Reply