在PHP中,将此字符串解析为关联数组的最有效方法是什么?
%STCITY^LASTNAME$FIRSTNAME$MIDDLENAME^ADDRESS1$ADDRESS2^?;UNIQUEID=YYMMDDYYMMDD=?
答案 0 :(得分:3)
与伊戈尔相似:
$regex = '/%(?<State>..)(?<City>[^^]*)\^(?<LastName>[^$]*)\$(?<FirstName>[^$]*)\$(?<MiddleName>[^^]*)\^(?<Address1>[^$]*)\$(?<Address2>[^^]*)\^\?;(?<UniqueId>[^=]*)=(?<Expiration>.{6})(?<Birthday>.{6})=/';
preg_match($regex, $str, $matches);
如果您运行示例:
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',
)
如您所见,它具有基于命名组(以及数字)的字符串键。