【问题标题】:Parse content from a file从文件中解析内容
【发布时间】:2013-02-23 12:36:58
【问题描述】:

我正在尝试解析具有以下内容的文件并将其显示在表格中。问题是我只能得到第一个租约节。我不知道如何获得其余的?有什么想法吗?

输入:

# The format of this file is documented in the dhcpd.leases manual page.
# This lease file was written by isc-dhcp-V3.0.3b1

lease 192.168.98.25 {
  starts 5 2012/10/05 21:18:41;
  ends 5 2012/10/05 22:48:15;
  tstp 5 2012/10/05 22:18:41;
  binding state free;
  hardware ethernet 78:d6:f0:c1:7f:b5;
  uid "\001x\326\360\301\177\265";
}
lease 192.168.10.1 {
  starts 5 2012/10/04 12:23:23;
  ends 5 2012/10/05 22:48:15;
  binding state active;
  next binding state free;
  hardware ethernet 56:a3:f0:d1:75:b5;
  uid "\001x\326\360\301\177\265";
}
....
....

输出:

 HW Address  |start time  | end time | IP 
 78:d6:f0:c1:7f:b5 | 2012/10/05 21:18:41 | 2012/10/05 22:48:15 | 192.168.98.25
 56:a3:f0:d1:75:b5 | 2012/10/04 12:23:23 | 2012/10/05 22:48:15 | 192.168.10.1

这是我迄今为止尝试过的:

$readfile = file('/etc/dhcp/dhcpd.leases',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$arstring = implode(" ",$readfile);

$regex=array();
preg_match_all("(lease\s*([0-9.]+)\s*{\s*starts\s*.?\s*([0-9/\s:]*).?\s*ends\s*.?\s*([0-9/\s:]*).*ethernet\s*([\w:]*))", $arstring, $regex,PREG_SET_ORDER);

这给了我:

[0] => Array
    (
        [0] => lease 192.168.98.25 {   starts 5 2012/10/05 21:18:41;   ends 5 2012/10/05 22:18:41;   tstp 5 2012/10/05 22:18:41;   binding state free;   hardware ethernet 78:d6:f0:c1:7f:b5;   uid "\001x\326\360\301\177\265"; } lease 192.168.98.25 {   starts 5 2012/10/05 22:54:15;   ends 5 2012/10/05 23:54:15;   binding state active;   next binding state free;   hardware ethernet 78:d6:f0:c1:7f:b5;   uid "\001x\326\360\301\177\265"; } lease 192.168.98.25 {   starts 5 2012/10/05 22:54:16;   ends 5 2012/10/05 23:54:16;   binding state active;   next binding state free;   hardware ethernet 78:d6:f0:c1:7f:b5
        [1] => 192.168.98.25
        [2] => 2012/10/05 21:18:41
        [3] => 2012/10/05 22:18:41
        [4] => 78:d6:f0:c1:7f:b5
    )

【问题讨论】:

  • 你不是已经拿到数据了吗?
  • 奇怪的是,您的模式中既没有开始/结束分隔符也没有修饰符。你试过了吗:preg_match_all("/your pattern here/mx"
  • i--,我尝试使用“/”分隔符,但结果更糟;该函数没有返回任何内容。

标签: php regex preg-match preg-match-all


【解决方案1】:

我不太了解 PHP,所以我不能给你确切的代码,但是如果你把它变成一个替换,然后在循环中执行它,用一个空白替换匹配的部分,直到没有任何剩余匹配,这可能会奏效。

【讨论】:

    【解决方案2】:

    我最终发现的问题是我没有逃避 .和 / 修饰符。

    这是我的工作正则表达式:

    $reg_str = '/(lease\s*([0-9\.]+)\s*{\s*starts\s*.?\s*([0-9\/\s:]*).?\s*ends\s*.?\s*([0-9\/:\s\w]*);[\r\n\s\w;]*ethernet\s*([\w:]*);?[\w\s\\\"0-9\s\r]*;?\s*[\w\-]*\s*"?([\w-]*)"?;?\s*})/ims';
    preg_match_all($reg_str, $arstring, $leases, PREG_SET_ORDER);
    

    感谢大家的帮助。

    【讨论】:

      猜你喜欢
      • 2016-11-20
      • 2012-01-19
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多