I have been trying to make a PHP code that counts the lines of text stored in a .txt file in a way so as it counts the total lines and the total spaces between paragraph's then echoes out each value along with a (Total Lines-Total Spaces) value at the end of the script unfortunately I can't get it to count spaces my current code looks like this:
<?php
$file="text.txt";
$spaceCount = 0;
$lineCount = 0;
$plainCount = $lineCount- $spaceCount;
$handle = fopen($file, "r");
while(!feof($handle))
{
$line = fgets($handle);
if(ctype_print($line))
{
$lineCount++;
}
else
{
$spaceCount++;
}
}
fclose($handle);
?>
<html>
<body>
<?php
echo "<table border=\"1\">";
echo "<tr>";
echo "<td> Total lines ".$lineCount."</td>";
echo "</tr>";
echo "<tr>";
echo "<td> Total Spaces ".$spaceCount." </td>";
echo "</tr>";
echo "<tr>";
echo "<td> Plain Text Count ".$plainCount."</td>";
echo "</tr>";
?>
</body>
</html>
This will be reading off a file that looks something like
TEXT, Text; Text
Info-info info.
Text More, Text
so there will be no pattern in the way it is written, Is there a way of doing this properly?
You can use the preg_match_all function to count the spaces and other matches, some as:
preg_match_all("/(\s)(\n)/", $string, $matches);
$spaces = count($matches[0]);
$lines = count($matches[1]);