Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I was wondering if anyone here could help me. I have the following string:

$str = 'unit1(field1,field2,field3),unit2(field4,field5,field6)';

I am trying to parse this string to create the following array:

array(
  'unit1' => array('field1', 'field2', 'field3')
  'unit2' => array('field4', 'field5', 'field6')
)

I am pretty hopeless with regex so I am not even sure where to start with this.

Thanks

share|improve this question
1  
I think you're missing some single quotes in the bottom unit2? – John Jul 17 at 3:18
To learn about regex you can start here regular-expressions.info. Then check out preg_match and preg_match_all on the PHP docs. Once you read all that try to build your own solution and come back with the code that failed and somebody might help. – elclanrs Jul 17 at 3:19
Your first code example isn't a string. – Jazza Jul 17 at 3:27
why not choose a more standardized format like JSON: [{"unit":"unit1", "fields":["field1","field2"]},...] and json_decode($str)? – Jan Dvorak Jul 17 at 3:57
add comment (requires an account with 50 reputation)

1 Answer

up vote 3 down vote accepted

You can do this without using regular expressions

 $str = 'unit1(field1,field2,field3),unit2(field4,field5,field6)';
 $str = trim($str, ")");
 $parts = explode("),",$str);
 $results = array();
 foreach($parts as $part){
      list($key, $value) = explode("(", $part,2);
      $results[$key] = explode(",", $value);
 }

Now the $results will contain your output as you specified.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.