Parsing advice, thanks in advance.



I am a little new to PHP programming, most of what I have learned are from prior examples. I have a file, C:\ups.log in which I would like to run a PHP script on daily with php.exe that will just parse all the information in it and tally up the individual matches. For instance:

C:\ups.log contains the following:


Notice the first 6 digits are always the same, its the 7-10th digits that are relevant (i.e 4123). Once this PHP script parses this file I would like a simple tally showing in the PHP.exe prompt:

4128 : 3
4123 : 2

that 4128 had 3 results and 4123 had 2. Any advice or knowledge of a similar script you can direct me to is very much appreciated.
Sounds easy enough. I'll assume you have all of the strings in an array. First, use substr() to strip out everything except the four digits you need. You can use array_walk() for this. Then you can use the handy function array_count_values() to count how many of each 4-digit string you have. Like so:

/* this is a callback function for array_walk ($key is ignored,
   might not be required?)
function get4digits(&$value, $key) {
   // get four digits starting at index 6
   $value = substr($string, 6, 4);

$strings_array = array(); // your array of strings goes here

// apply get4digits() to each element in $strings_array
array_walk($strings_array, 'get4digits');

// count how many of each value there is
$value_counts = array_count_values($strings_array);

/* optionally sort the resulting array, if you'd like */

// print out the counts:
foreach($value_counts as $key => $value) {
   echo $key . ' : ' . $value;

Pretty simple. Those array_walk() and array_count_values() functions are quite handy.
If you don't have the file in an array yet, you could also use the following to do it all:

if($ary = file('c:\ups.log')) {
	foreach(array_keys($ary) as $key)
		$ary[$key] = substr($ary[$key],6,4);
	foreach(array_count_values($ary) as $key=>$value)
		print($key.': '.$value.'<br>');

This will use the FILE function to open the file and place all the lines into an array. It will then loop through the array and keep only the 7-10 characters of the string. It will then count the array values and print them out.

Good luck
Thank you much for your most sufficient replies. Will give those suggestions a try.