在PHP中将纯文本解析为关联数组

时间:2012-03-14 23:05:38

标签: php

我一直在努力,但尚未找到任何解决方案。我需要将这样的字符串解析为关联数组(PHP)

  

结果:ssl_card_number = 35 * ** * 0000 ssl_exp_date = 1212   ssl_amount = 33.55 ssl_invoice_number = 0 ssl_description =   ssl_company =某些公司ssl_first_name = John ssl_last_name = Cater   ssl_avs_address =测试St. ssl_address2 = ssl_city = Sandy ssl_state =犹他州   ssl_avs_zip = 84075 ssl_country =美国ssl_phone =   ssl_email=johncarter@gmail.com ssl_result = 0   ssl_result_message = APPROVED   ssl_txn_id = 00000000-0000-0000-0000-00000000000   ssl_approval_code = 123456 ssl_cvv2_response = P ssl_avs_response = X   ssl_account_balance = 0.00 ssl_txn_time = 03/14/2012 06:58:27 PM

这个字符串来自Merchant Service(上面的那个包含假数据)所以我需要解析它并达到像这样的值

$card_number = $parsed["ssl_card_number"];

我怎样才能完成它?注意:所有键都以ssl_开头,它可能在某个地方有用。

1 个答案:

答案 0 :(得分:2)

$string = 'ssl_card_number=35****0000 ssl_exp_date=1212 ssl_amount=33.55 ssl_invoice_number=0 ssl_description= ssl_company=Some Company ssl_first_name=John ssl_last_name=Cater ssl_avs_address=Test St. ssl_address2= ssl_city=Sandy ssl_state=Utah ssl_avs_zip=84075 ssl_country=United States ssl_phone= ssl_email=johncarter@gmail.com ssl_result=0 ssl_result_message=APPROVED ssl_txn_id=00000000-0000-0000-0000-00000000000 ssl_approval_code=123456 ssl_cvv2_response=P ssl_avs_response=X ssl_account_balance=0.00 ssl_txn_time=03/14/2012 06:58:27 PM';

$result = array();
$arr = preg_split('/\s+ssl_/', $string);
foreach ($arr as $l) {
        $tmp = explode('=', $l, 2);
        $result['ssl_' . $tmp[0]] = $tmp[1];
}
print_r($result);