tags:

views:

49

answers:

1

In PHP what is the most efficient way to parse this string into an associative array?

%STCITY^LASTNAME$FIRSTNAME$MIDDLENAME^ADDRESS1$ADDRESS2^?;UNIQUEID=YYMMDDYYMMDD=?
+2  A: 

Similar to Igor:

$regex = '/%(?<State>..)(?<City>[^^]*)\^(?<LastName>[^$]*)\$(?<FirstName>[^$]*)\$(?<MiddleName>[^^]*)\^(?<Address1>[^$]*)\$(?<Address2>[^^]*)\^\?;(?<UniqueId>[^=]*)=(?<Expiration>.{6})(?<Birthday>.{6})=/';
preg_match($regex, $str, $matches);

If you run the example:

array (                    
  0 => '%STCITY^LASTNAME$FIRSTNAME$MIDDLENAME^ADDRESS1$ADDRESS2^?;UNIQUEID=YYMMDDYYMMDD=',
  'State' => 'ST',                                                                        
  1 => 'ST',                                                                              
  'City' => 'CITY',                                                                       
  2 => 'CITY',                                                                            
  'LastName' => 'LASTNAME',                                                               
  3 => 'LASTNAME',                                                                        
  'FirstName' => 'FIRSTNAME',
  4 => 'FIRSTNAME',
  'MiddleName' => 'MIDDLENAME',
  5 => 'MIDDLENAME',
  'Address1' => 'ADDRESS1',
  6 => 'ADDRESS1',
  'Address2' => 'ADDRESS2',
  7 => 'ADDRESS2',
  'UniqueId' => 'UNIQUEID',
  8 => 'UNIQUEID',
  'Expiration' => 'YYMMDD',
  9 => 'YYMMDD',
  'Birthday' => 'YYMMDD',
  10 => 'YYMMDD',
)

As you can see, it has string keys based on the named groups (as well as numeric).

Matthew Flaschen
This is an excellent answer! Is there a way to make it without the numeric?
I don't know a way to not set the numerics. You could remove them, but that's probably pointless.
Matthew Flaschen
Yeah, I just removed them when I formatted the output into a new array. Thanks again!
upped answer for nice regexin' ;)
flungabunga