php+regex split into array by sections


Keywords:php 


Question: 

I need a help with php+regex split from input text file into array: using preg_match_all

/(SUNDAY|MONDAY|TUESDAY|WEDNESDAY|THURSDAY|FRIDAY|SATURDAY)\R(\d{4})-([0-9]|0[1-9]|[1-2][0-9])-([0-9]|0[1-9]|[1-2][0-9]|3[0-1])\R(.*?)\R(.*?)\R\R/mi

day -> all day agenda, like this:

$x = array(
  '2017-03-21' => "9:00 Meeting\n12:00 Lunch",
  '2017-03-27' => "11:00 Meeting"
)

input file:

 some of text

 MONDAY
 2017-03-21
 9:00 Meeting
 12:00 Lunch

 FRIDAY
 2017-03-27
 11:00 Meeting

 END

 more text

3 Answers: 

By this regex:

(?<date>\d{4}-\d{2}-\d{2})\n(?<todos>[\s\S]*?)\n\n

You're capturing dates in 'date' (match[1]) group and other todo texts in 'todo'(match[2])

Demo:

 

You can try this:

\w+\n(?!\n)^(\d{4}(?:-\d{2}){2})((\n\d+:\d+\s+\w+)+)

Explanation

 

Use the following approach(preg_match_all and array_combine functions):

$re = '/\b[A-Z]+\s(\d{4}-\d{2}-\d{1,2})\s(.+?)(?=\n\n|$)/s';
$result = [];

preg_match_all($re, $str, $matches);
if (isset($matches[1]) && isset($matches[2])) {
    $result = array_combine($matches[1], $matches[2]);
}

print_r($result);

The output:

Array
(
    [2017-03-21] => 9:00 Meeting
12:00 Lunch
    [2017-03-27] => 11:00 Meeting
)