user3932764
user3932764

Reputation: 15

Calculating how many times a string repeats in a file?

I'm trying to make a script. The important thing is that it always writes in a text document, so what I want to do is count how many times it wrote in that document, somekind like calculating the rows from a DB.

It's this possible?

$myFile = "log.txt";
$OS = "It is running: ";
$ID = "System ID: ";
$Skip = "<br />";
$link = '<a href="';
$link2 = '/status.txt"> Click here to view if it is online</a>';
$fh = fopen($myFile, 'a') or die("can't open file");
$menu_text = $_POST['field1'];
$menu_text2 = $_POST['field2'];

if (empty($menu_text2)) {
    echo "No Data Has Been Posted";
    fclose($fh);
}
else {
    $stringData = $OS . $menu_text . $Skip . $ID . $menu_text2 . $link . $menu_text2 . $link2 . $Skip;
    fwrite($fh, $stringData);
    fclose($fh);
    print_r($menu_text2);
    mkdir($menu_text2, 0777);
}

Upvotes: 0

Views: 56

Answers (2)

Dinu Sorin
Dinu Sorin

Reputation: 215

I see you write a <br /> at the end of each line. If no other variable you have in $stringData = ... will have <br /> in them you could open the file and count how many times the <br /> occurs.

If you might have <br /> (and you might as menu_text and menu_text2 are user inputs) then you should also add a new line and then count the lines in the file. Note that you will need to read the whole file in order to get the count which for large files might not be good.

Another thing you could do is just store the count in another file.

Upvotes: 1

Cristian D
Cristian D

Reputation: 691

$file = fopen($myFile, "r");
$count = 0;
while($row = fgets($file)) {
   if(strstr($row, "<br />") !== false)
       $count ++;
}
echo $count;

Upvotes: 0

Related Questions