【问题标题】:php regex parsing a string to find substrings that match patternsphp正则表达式解析字符串以查找匹配模式的子字符串
【发布时间】:2015-01-24 20:09:12
【问题描述】:

我需要解析以下字符串以选择各种数据项,以便将它们放入数据对象中。我目前正在使用 PHP,但我对字符串解析没有太多经验,所以想知道是否有人能指出我正确的方向。

要解析的示例字符串:

For explanation of columns, see `full-story: with notes'.

===============================================================================
Database 12-13-2

Table 21111C:
21111C No module scaling factor applied
------------------------------------------------------------------------------------------------
      Weighting     |1    |1    |1    |1    |1    |1    |1    |1    |1    |1    |10      |
------------------------------------------------------------------------------------------------
      Denominator   |20   |20   |20   |20   |20   |20   |20   |20   |20   |20   |%       |%
------------------------------------------------------------------------------------------------
Email Name          |Ex1D |Ex2D |Ex3D |Ex4D |Ex5D |Ex6D |Ex7D |Ex8D |Ex9D |Ex10D|Total   |Marked
================================================================================================
mahmoou1 Mahmood,Usm|17   |20   |10   |16   |19   |16   |20   |13   |14   |7    |76      |76

Table 22712L:
22712L Final dynamic scaling factor (range 60%-65%) is 1.00
------------------------------------------------------------
      Weighting     |1    |1    |1    |1    |4       |
------------------------------------------------------------
      Denominator   |20   |20   |20   |20   |%       |%
------------------------------------------------------------
Email Name          |14D  |16D  |Ex7D |Ex9D |Total   |Marked
============================================================
mahmoou1 Mahmood,Usm|13   |11c  |14   |14   |65c     |65


===============================================================================
End of query results

我正在尝试将诸如 DATABASE ID、表 ID 以及权重/分母/标记列表等信息提取到我为此创建的 PHP 数据对象中。

我已经查看了 PHP 中的 preg_* 函数,但我仍在努力寻找如何以最好的方式做到这一点。我需要让任何可能需要查看/更新它的未来程序员能够理解代码。

【问题讨论】:

  • 我建议你逐行工作。
  • @vks 我想提取例如 ["21111C", "22712"] 这样我就可以将它们添加到数据对象中。也是“范围 60%-65%”。还有标记,例如 [13, 11c, 14, 14, 65c, 65]。等等。

标签: php regex string parsing


【解决方案1】:
where $string is your test string:

// Database ID
preg_match_all("(?<=Database )[\d-]+\b", $string, $matches);
foreach($matches[0] as $test){
   echo $test . "\n";
}

// Table(s) ID(s)
preg_match_all("(?<=Table )[\w]+(?=[:])", $string, $matches);
foreach($matches[0] as $test){
   echo $test . "\n";
}

【讨论】:

    猜你喜欢
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多