<?
$str = <<<EOT
FooID: 123456
Name: Chuck
When: 01/02/2013 01:23:45
InternalID:
User Message: Hello,
this is nillable, but can be quite long. Text can be spread out over many lines
This\: works too. And can start with any number of \\n's. It can be empty, too.
What's worse, though is that this CAN contain colons (but they're _"escaped"_
using `\`) like so `\:`, and even basic markup!
EOT ;
$prevKey = '' ;
$split = ': ' ;
for ( $i = 0 , $arrlen = sizeof ( $arr ) ; $i < $arrlen ; $i ++ ) { $keyValuePair = explode ( $split , $arr [ $i ] , 2 ) ; // ?: Is this a valid key/value pair
if ( sizeof ( $keyValuePair ) < 2 && $i > 0 ) { // -> Nope, append the value to the previous key's value
$output [ $prevKey ] .= "\n " . $keyValuePair [ 0 ] ;
}
else {
// -> Maybe
// ?: Did we miss an escaped colon
if ( substr ( $keyValuePair [ 0 ] , - 1 ) === '\\' ) { // -> Yep, this means this is a value, not a key/value pair append both key and
// value (including the split between) to the previous key's value ignoring
// any colons in the rest of the string (allowing dates to pass through)
$output [ $prevKey ] .= "\n " . $keyValuePair [ 0 ] . $split . $keyValuePair [ 1 ] ;
}
else {
// -> Nope, create a new key with a value
$output [ $keyValuePair [ 0 ] ] = $keyValuePair [ 1 ] ;
$prevKey = $keyValuePair [ 0 ] ;
}
}
}
PD8KJHN0ciA9IDw8PEVPVApGb29JRDogMTIzNDU2Ck5hbWU6IENodWNrCldoZW46IDAxLzAyLzIwMTMgMDE6MjM6NDUKSW50ZXJuYWxJRDogClVzZXIgTWVzc2FnZTogSGVsbG8sCnRoaXMgaXMgbmlsbGFibGUsIGJ1dCBjYW4gYmUgcXVpdGUgbG9uZy4gVGV4dCBjYW4gYmUgc3ByZWFkIG91dCBvdmVyIG1hbnkgbGluZXMKVGhpc1w6IHdvcmtzIHRvby4gQW5kIGNhbiBzdGFydCB3aXRoIGFueSBudW1iZXIgb2YgXFxuJ3MuIEl0IGNhbiBiZSBlbXB0eSwgdG9vLgpXaGF0J3Mgd29yc2UsIHRob3VnaCBpcyB0aGF0IHRoaXMgQ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aW5nIChhbGxvd2luZyBkYXRlcyB0byBwYXNzIHRocm91Z2gpCiAgICAgICRvdXRwdXRbJHByZXZLZXldIC49ICJcbiIgLiAka2V5VmFsdWVQYWlyWzBdIC4gJHNwbGl0IC4gJGtleVZhbHVlUGFpclsxXTsKICAgIH0KICAgIGVsc2UgewogICAgICAvLyAtPiBOb3BlLCBjcmVhdGUgYSBuZXcga2V5IHdpdGggYSB2YWx1ZQogICAgICAkb3V0cHV0WyRrZXlWYWx1ZVBhaXJbMF1dID0gJGtleVZhbHVlUGFpclsxXTsKICAgICAgJHByZXZLZXkgPSAka2V5VmFsdWVQYWlyWzBdOwogICAgfQogIH0KfQoKdmFyX2R1bXAoJG91dHB1dCk7
stdout
array(5) {
["FooID"]=>
string(6) "123456"
["Name"]=>
string(5) "Chuck"
["When"]=>
string(19) "01/02/2013 01:23:45"
["InternalID"]=>
string(0) ""
["User Message"]=>
string(293) "Hello,
this is nillable, but can be quite long. Text can be spread out over many lines
This\: works too. And can start with any number of \n's. It can be empty, too.
What's worse, though is that this CAN contain colons (but they're _"escaped"_
using `\`) like so `\:`, and even basic markup!"
}