您可以尝试使用preg_split:
$string = <<<STR
2013-06-04 12:12:12 - Name1 Surname1 - Activity1
2013-06-04 12:12:12 - Name2 Surname2 - Activity2
2013-06-04 12:12:12 - Name3 Surname3 - Multiline Activity1
Multiline Activity2
Multiline Activity3
2013-06-04 12:12:12 - Name4 Surname4 - Activity4
STR;
$arr = preg_split("/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) - (.*) - (.*)[\r\n]?/", $string, null, PREG_SPLIT_DELIM_CAPTURE);
$arr = array_filter($arr);
print_r($arr);
输出:
Array
(
[1] => 2013-06-04 12:12:12
[2] => Name1 Surname1
[3] => Activity1
[5] => 2013-06-04 12:12:12
[6] => Name2 Surname2
[7] => Activity2
[9] => 2013-06-04 12:12:12
[10] => Name3 Surname3
[11] => Multiline Activity1
[12] => Multiline Activity2
Multiline Activity3
[13] => 2013-06-04 12:12:12
[14] => Name4 Surname4
[15] => Activity4
)
实际用法示例:
$i = -1;
$result = array();
foreach($arr as $value) {
if(preg_match("/(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})/", $value)) {
// 1st element - datetime
$i++;
$result[$i]['datetime'] = $value;
} elseif(!isset($result[$i]['name'])) {
// 2nd element - name
$result[$i]['name'] = $value;
} else {
// 3rd element - activities separated by comma
if(!isset($result[$i]['activities'])) {
$result[$i]['activities'] = $value;
} else {
$result[$i]['activities'] .= ', ' . $value;
}
}
}
print_r($result);
输出:
Array
(
[0] => Array
(
[datetime] => 2013-06-04 12:12:12
[name] => Name1 Surname1
[activities] => Activity1
)
[1] => Array
(
[datetime] => 2013-06-04 12:12:12
[name] => Name2 Surname2
[activities] => Activity2
)
[2] => Array
(
[datetime] => 2013-06-04 12:12:12
[name] => Name3 Surname3
[activities] => Multiline Activity1
, Multiline Activity2
Multiline Activity3
)
[3] => Array
(
[datetime] => 2013-06-04 12:12:12
[name] => Name4 Surname4
[activities] => Activity4
)
)