regex - PHP - Pars Excel and explode a string by commas


Keywords:php 


Question: 

I'm parsing an Excel file by PHPExcel. The Excel file has two columns A and B. As follows:

________________________
|     A     |     B    |
________________________
| 987654321 | 55,12,11 |
| 789456123 |   1,2,3  |
| 998877665 | 10,11,12 |
| 112233345 |     8    |
________________________

PHPExcel output is as follows for $array1:

Array
(
    [0] => "987654321","55,12,11"
    [1] => "789456123","1,2,3"
    [2] => "998877665","10,11,12"
    [3] => "112233345","8"
)

I use this code to parse $array1:

$res = array();
foreach ($array1 as $key => $value)
{
   if ($arr != '')
   {
      $res[$key] = explode(",", str_replace('"', '', $value));
   }
}

I want to get this result:

Array
(
    [0] => Array
        (
            [0] => 987654321
            [1] => 55,12,11
        )

    [1] => Array
        (
            [0] => 789456123
            [1] => 1,2,3
        )
) //etc...

But instead I get:

Array
(
    [0] => Array
        (
            [0] => 987654321
            [1] => 55
            [2] => 12
            [3] => 11
        )

    [1] => Array
        (
            [0] => 789456123
            [1] => 1
            [2] => 2
            [3] => 3
        )
) //etc..

How can I conclude?


2 Answers: 

Treat it as CSV as that's how it's coming from Excel:

foreach($array1 as $key => $value) {
    $res[$key] = str_getcsv($value);
}
 

You can use:

$res[$key] = explode('","', trim($value, '"'));

Note that parsing comma delimited sections like this will fail as soon as you are trying to separate strings instead of integers.