PHP 正则表达式解析字符串以查找与模式匹配的子字符串


php regex parsing a string to find substrings that match patterns

我需要解析以下字符串以选择各种数据项,以便将它们放入数据对象中。我目前正在使用 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

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

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

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";
}