scanf formatting issue
Posted
by
da_rockwilder
on Stack Overflow
See other posts from Stack Overflow
or by da_rockwilder
Published on 2011-03-09T15:56:15Z
Indexed on
2011/03/09
16:10 UTC
Read the original article
Hit count: 231
I have a log file with the following format:
INFO 2011-03-09 10:26:15,270 [user] message
I want to parse the log file using PHP:
// assume file exists and all that
$handle = fopen("log_file.txt", "r");
while ($line_data = fscanf($handle, "%s %s %s [%s] %s\n")) {
var_dump($line_data);
}
fclose($handle);
When I run this code I get:
[0]=>
array(5) {
[0]=> string(4) "INFO"
[1]=> string(10) "2011-03-09"
[2]=> string(12) "10:26:15,270"
[3]=> string(5) "user]"
[4]=> NULL
}
// snip
It appears the closing bracket in the format string ("%s %s %s [%s] %s") is disrupting the rest of the line from getting parsed. I checked the PHP docs for scanf (as suggested by fscanf), and I didn't see anything mentioning having to escape a left bracket.
Any suggestions on how to get the 4th and 5th elements to look like "user" and "message" respectively?
© Stack Overflow or respective owner