简体   繁体   中英

php regex parsing a string to find substrings that match patterns

I need to parse the following string to select various items of data out so I can place them into a data object. I am using PHP at the moment but I don't have much experience with string parsing so was wondering if someone can point me into the right direction.

Sample string to parse:

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

I am trying to extract information such as the DATABASE ID, table ID, and then the lists of Weightings / denominators / marks into a PHP data object I have created for this.

I have looked at the preg_* functions in PHP but I am still struggling to see how I would do this in the best way. I need the code to be understandable to any future programmers who may need to view / update it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM