fork download
  1. <?
  2. $str = <<<EOT
  3. FooID: 123456
  4. Name: Chuck
  5. When: 01/02/2013 01:23:45
  6. InternalID:
  7. User Message: Hello,
  8. this is nillable, but can be quite long. Text can be spread out over many lines
  9. This\: works too. And can start with any number of \\n's. It can be empty, too.
  10. What's worse, though is that this CAN contain colons (but they're _"escaped"_
  11.  
  12.  
  13. using `\`) like so `\:`, and even basic markup!
  14. EOT;
  15.  
  16. $arr = explode("\n", $str);
  17.  
  18. $prevKey = '';
  19. $split = ': ';
  20. $output = array();
  21. for ($i = 0, $arrlen = sizeof($arr); $i < $arrlen; $i++) {
  22. $keyValuePair = explode($split, $arr[$i], 2);
  23. // ?: Is this a valid key/value pair
  24. if (sizeof($keyValuePair) < 2 && $i > 0) {
  25. // -> Nope, append the value to the previous key's value
  26. $output[$prevKey] .= "\n" . $keyValuePair[0];
  27. }
  28. else {
  29. // -> Maybe
  30. // ?: Did we miss an escaped colon
  31. if (substr($keyValuePair[0], -1) === '\\') {
  32. // -> Yep, this means this is a value, not a key/value pair append both key and
  33. // value (including the split between) to the previous key's value ignoring
  34. // any colons in the rest of the string (allowing dates to pass through)
  35. $output[$prevKey] .= "\n" . $keyValuePair[0] . $split . $keyValuePair[1];
  36. }
  37. else {
  38. // -> Nope, create a new key with a value
  39. $output[$keyValuePair[0]] = $keyValuePair[1];
  40. $prevKey = $keyValuePair[0];
  41. }
  42. }
  43. }
  44.  
  45. var_dump($output);
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
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!"
}