What happens if (if it can happen!) the data looks like:
lorem ipsum
Your Name: Joe Bloggs
Your Address: 1 Big Street
Myhamlet
Mytown
Preferred Method of receiving information: Carrier Pidgeon
Comments: [COLOR="DarkRed"]This is a comment
but this one is too: we know that
comments can span multiple lines but
what about colons?[/COLOR]
lorem ipsum dolor sit amet
kind of combining some previous answers, but possibly helpful:
$str = '
lorem ipsum
Your Name: Joe Bloggs
Your Address: 1 Big Street
Myhamlet
Mytown
Preferred Method of receiving information: Carrier Pidgeon
Comments: This is a comment
But this one is too: we know that
comments can span multiple lines but
what about colons?
lorem ipsum dolor sit amet
';
$myKeys = array(
'Your Address' => "Address",
"Your Name" => "Name",
"Preferred Method of receiving information" => "PrefMethod",
'Comments' => 'comments'
);
$terms = implode(':|', array_keys($myKeys));
$results = array();
foreach($myKeys as $key => $val) {
if (preg_match('#(?:^|\
)('.$key.'):\\s*(.+?)\
('.$terms.':|$)#s', $str, $m)) {
$results[$val] = $m[2];
}
}
// results array should contain what you need?
If your original split used a regex, then perhaps that can be modified rather than create a second or third one - or, maybe we can treat the whole thing as lines to array elements and work though them.
Unfortunately it’s impossible to get rid of that last line - there is no way to know if it is part of the comment field or not. You could alter the code to ignore everything after a double line break, but in a comment field a double line break would be perfectly possible. I would suggest trying it on some real world data and see how it goes.
$str = 'Your Name: Joe Bloggs
Your Address: 1 Big Street
Myhamlet
Mytown
Preferred Method of receiving information: Carrier Pidgeon
Comments: This is a comment
But this one is too: we know that
comments can span multiple lines but
what about colons?
lorem ipsum dolor sit amet
';
$myKeys = array(
'Your Address' => "Address",
"Your Name" => "Name",
"Preferred Method of receiving information" => "PrefMethod",
'Comments' => 'comments'
);
$terms = implode(':|', array_keys($myKeys));
$results = array();
foreach($myKeys as $key => $val) {
if (preg_match('#(?:^|\
)('.$key.'):\\s*(.+?)\
('.$terms.':|\
|$)#s', $str, $m)) {
$results[$val] = $m[2];
}
}