How to split a string into space, numbers and quotation marks in PHP?

I am parsing a string in PHP that has the following pattern

VARIABLE Key1 Value1 Key2 Value2 Key3 Value3 ... 

looks like:

 JOBGRADE 'P' 'Parttime Employee' 'C' 'Customer Support' 

OR

 SOMEVARIABLE 1 "Value1" 2 'Value2' 

This line begins with a line without quotes and may contain single or double quotes and / or numbers. It can have one pair pair with several keys.

I need to break the string in two ways:

The first is to get a string without quotes, which is not numeric.

The second, to extract a numerical value and / or quoted strings - can be single or dobule

So I need

  • JOBGRADE
  • P: Part-time employee
  • C: Customer Service

OR

  • SOMEVARIABLE
  • 1: Value 1
  • 2: Value2

My thoughts:

I thought about splitting a string and repeating its test:

for 1: if the value is not numeric and is not quoted, this is the name of the variable

for 2+: Not sure if this is an easy way to do this, because I have to determine the difference between keys and values:

Question

How can I distinguish key / value?

+4
source share
2 answers

Treat it like a CSV and iterate over it to share it. Variable [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" } 
+11
source

first use explode () in the variable string to get all parts separated by one space: http://php.net/manual/en/function.explode.php

 $variables = explode("JOBGRADE 'P' 'Parttime Employee' 'C' 'Customer Support'", ' '); 

// I would not use the first element, so I delete it, save it as a title for later

 $var_name = array_shift($variables); 

// secondly, iterate over the elements (step 2) and add the key and value to the resulting array

 $result = array(); for ($i = 0; $i < count($variables); $i = $i +2) { $result[$variables[$i]] = $variables[$i + 1]; } print_r($result); 
+1
source

All Articles