Last active
November 17, 2018 02:22
-
-
Save JeffTomlinson/661d6691923557d62f7ed2f66a020438 to your computer and use it in GitHub Desktop.
Parse multiline pipe delimited strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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