scanf格式问题
我有一个具有以下格式的日志文件:
INFO 2011-03-09 10:26:15,270 [user] message
我想使用 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);
当我运行此代码时,我得到:
[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
它出现在格式字符串中的右括号 ("%s %s %s [%s] % s") 正在中断该行的其余部分的解析。我检查了 PHP 文档中的 scanf (按照 fscanf 的建议),但没有看到任何提到必须转义左括号的内容。
关于如何使第四个和第五个元素分别看起来像“用户”和“消息”有什么建议吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用该格式
可以防止第四个元素采用任何
]
字符(当然,这假设名称中没有]
字符)。(使用 sscanf 的示例:http://ideone.com/lJHYa)
%[abc] 格式说明符将使函数读取仅包含字符
a
、b
或c
的字符串。相反,%[^xyz]
将使函数读取一个不具有任何x
、y
的字符串和z
。因此,上面的
%[^]]
将读取一个字符串,直到遇到]
。Use the format
to prevent the 4th element taking any
]
character (of course this assumes there is no user having a]
in the name).(Example using sscanf: http://ideone.com/lJHYa)
The
%[abc]
format specifiers will make the function read a string consists of only charactersa
,b
orc
. The inverse,%[^xyz]
will make the function read a string not having any ofx
,y
andz
.Therefore, the
%[^]]
above will read a string until hitting a]
.使用正则表达式...如果您确实想要 fscanf,请转义括号
http:// pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html
:
use regular expressions... if you really want fscanf, escape the bracket
http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html
: