I am parsing a string in PHP that has the following pattern
VARIABLE Key1 Value1 Key2 Value2 Key3 Value3 ...
similar to:
JOBGRADE 'P' 'Parttime Employee' 'C' 'Customer Support'
OR
SOMEVARIABLE 1 "Value1" 2 'Value2'
This line starts with an unquoted string and can have single or double quoted strings and/or numbers. It can have one to multiple key value pairs.
I need to split the string in 2 ways:
The first to get the unquoted string that is not numeric.
The second to extract the numeric value and/or quoted strings - can be single or dobule
Thus I need
OR
My Thoughts:
I thought about splitting the string and iterating through it to test:
for 1: If value is not numeric and not quoted it is the variable name
for 2+: Not sure the easy way to do this because I must detect the difference between the keys and values:
Question:
How can I distinguish between the key/value?
Treat it as CSV, and iterate over it to divide it up. The variable is [0]
, keys are odd starting from [1]
, values even from [2]
.
var_dump(str_getcsv("JOBGRADE 'P' 'Parttime Employee' 'C' 'Customer Support'",
' ', "'"));
array(5) { [0]=> string(8) "JOBGRADE" [1]=> string(1) "P" [2]=> string(17) "Parttime Employee" [3]=> string(1) "C" [4]=> string(16) "Customer Support" }
first use explode() on the variable string to get all parts seperated by one space: http://php.net/manual/en/function.explode.php
$variables = explode("JOBGRADE 'P' 'Parttime Employee' 'C' 'Customer Support'", ' ');
//i wouldn't use the first item so remove it, keep as as title for later
$var_name = array_shift($variables);
//secondly, loop over items (step 2) and add to resulting array the key & value
$result = array();
for ($i = 0; $i < count($variables); $i = $i +2) {
$result[$variables[$i]] = $variables[$i + 1];
}
print_r($result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With