Forum Moderators: coopster

Message Too Old, No Replies

opening text file and counting

         

ahmed24

11:39 am on Jun 16, 2009 (gmt 0)

10+ Year Member



hey everyone,

i have a log file that has one word entries in each line of the text file. i want to be able to determine how many times the word alpha appears to be in the log file and if the number of times it appears is an odd number then echo odd and if if it's even number then echo Even.

any ideas how I can do this?

thanks

jatar_k

12:58 pm on Jun 16, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



pull it into an array and then count them

how many words/lines are there in the file?

why not use a db?

ahmed24

1:18 pm on Jun 16, 2009 (gmt 0)

10+ Year Member



thanks for your reply. theres only about max 200 lines in the text file, so dont really want to create a database just for it.

is there any sample code on the internet that may help me do this?

jatar_k

1:24 pm on Jun 16, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



[php.net...]

ahmed24

2:59 pm on Jun 16, 2009 (gmt 0)

10+ Year Member



i've done it like this:

$logfile = file_get_contents ( "test.txt" );
$count = substr_count($logfile, "alpha");

if ($count % 2) {
echo "Odd";
} else {
echo "Even";
}

the problem i am having is that if the word alphabet or alphanumeric exists then it also counts that as the word alpha.

can anyone tell me how i can limit it to find exactly the word alpha?

jatar_k

3:16 pm on Jun 16, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



with something as short as 200 you could loop it every time using a while and just strcmp and count it then output the even/odd result

coopster

3:46 pm on Jun 16, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



file_get_contents brings it into a string so now just use preg_match_all to get a count rather than substr_count. Regular expression matching can use word boundaries.

idfer

7:18 pm on Jun 16, 2009 (gmt 0)

10+ Year Member



If you're on a Linux/Unix box and can call exec(), this works too:

exec('[i]path-to-bindir[/i]/fgrep -wc alpha [i]logfile[/i]', $res); 
echo "{$res[0]} occurences found";

path-to-bindir is usually /bin or /usr/bin, i think.