Skip to content

Instantly share code, notes, and snippets.

@JeffTomlinson
Last active November 17, 2018 02:22
Show Gist options
  • Save JeffTomlinson/661d6691923557d62f7ed2f66a020438 to your computer and use it in GitHub Desktop.
Save JeffTomlinson/661d6691923557d62f7ed2f66a020438 to your computer and use it in GitHub Desktop.
Parse multiline pipe delimited strings
/**
* Extracts an array of key/value pairs from the input string.
*
* @param string $string
* The input string to extract values from.
*
* @return array
* An array of key/value pairs.
*/
function parse_multiline_pipe_delimited_string($string) {
$values = [];
$list = explode("\n", $string);
$list = array_map('trim', $list);
$list = array_filter($list, 'strlen');
foreach ($list as $text) {
// Parse pipe delimited text string and add key/value pairs to the output.
if (preg_match('/(.*)\\|(.*)/', $text, $matches)) {
// Trim key and value to avoid unwanted spaces issues.
$key = trim($matches[1]);
$value = trim($matches[2]);
$values[$key] = $value;
}
}
return $values;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment