正则表达式分析日志

$data = "
Dec  25 10:02:10  192.168.0.213  syslog-ng[22683]:  syslog-ng  starting  up;  version='2.0.6'
Dec  25  10:02:23  192.168.0.213  CRON[22595]:  pam_unix(cron:session):  session  closed  for  user  www-data 
Dec  25  10:02:51  192.168.0.213  shutdown[22761]:  shutting  down  for  system  reboot 
Dec  25  10:02:54  192.168.0.213  init:  Switching  to  runlevel:  6 
Dec  25  10:03:02  192.168.0.213  kernel:  CPU0:  Temperature/speed  normal 
Dec  25  10:03:10  192.168.0.213  watchdog[2962]:  stopping  daemon  (5.4) 
Dec  25  10:03:10  192.168.0.213  wd_keepalive[22852]:  starting  watchdog  keepalive  daemon  (5.4):  int=10  alive=(null)  realtime=yes 
Dec  25  10:03:10  192.168.0.213  wd_keepalive[22852]:  stopping  watchdog  keepalive  daemon  (5.4) 
Dec  25  10:03:23  192.168.0.213  rpc.statd[2040]:  Caught  signal  15,  un-registering  and  exiting. 
Dec  25  10:03:24  192.168.0.213  ntop[2683]:    CLEANUP[t3054491312]:  ntop  caught  signal  15 
Dec  25  10:03:24  192.168.0.213  ntop[2683]:    THREADMGMT[t3054491312]:  ntop  RUNSTATE:  SHUTDOWN(7)
"; 
preg_match_all('/([\w]{3}[\s]+[\d]{1,2}[\s]+[\d:]{5,8})[\s]+([0-9\.]{7,15})[\s]+([\w\-\.]+?)(?(?=\[[\d]+\])\[([\d]+)\]):(.+)/i',$data,$a);
print_r($a);
# 讲解
#'/([\w]{3}[\s]+[\d]{1,2}[\s]+[\d:]{5,8})[\s]+([0-9\.]{7,15})[\s]+([\w\-\.]+?)(?(?=\[[\d]+\])\[([\d]+)\]):(.+)/i'
# 时间匹配开始
# [\w]{3}     1,匹配三位任一“字”的字符
# [\s]+       2,匹配多位空白符
# [\d]{1,2}     3,匹配由一到两位的数字
# [\s]+        4,匹配多位空白符
# [\d:]{5,8}    5,匹配五到八位由十进制数字和冒号组成的字符串 ;
# 时间匹配结束
# [\s]+       1,匹配多位空白符
# Ip匹配开始
# [\d\.]{7,15}  1,匹配七到十五位由十进制数字和点号组成的字符串 ;
# Ip匹配结束
# [\s]+       1,匹配多位空白符
# 程序匹配开始
# ([\w\-\.]+?)  1,匹配任一'字',点号和'-'号.
# 程序匹配结束
# 端口匹配开始
# (?(?=\[[\d]+\])\[([\d]+)\]) 1,条件匹配 如有匹配 [一位或多位十进制数字] 的字符串 则取出数字,即执行后面的 \[([\d]+)\] 匹配.
# 端口匹配结束
# : 1,匹配冒号
# 描述匹配开始
# (.+)     1,匹配除了换行符外的任意一个字符(默认情况下)
# 描述匹配结束
# /i        1,i 模式修正符 “如果设定此修正符,模式中的字符将同时匹配大小写字母” 即 不区分大小写
 

你可能感兴趣的:(正则表达式)