Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by space, numbers, and quotes in PHP?

Tags:

regex

php

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

  1. JOBGRADE
  2. P:Parttime Employee
  3. C:Customer Support

OR

  1. SOMEVARIABLE
  2. 1:Value1
  3. 2:Value2

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?

like image 795
Todd Moses Avatar asked Dec 17 '22 19:12

Todd Moses


2 Answers

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"
}
like image 60
Ignacio Vazquez-Abrams Avatar answered Jan 03 '23 14:01

Ignacio Vazquez-Abrams


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);
like image 26
filsterjisah Avatar answered Jan 03 '23 13:01

filsterjisah