dirk
dirk

Reputation: 2306

php explode by comma ignore thousands seperator

I am scraping the following kind of strings from an external resource which I can't change:

["one item",0,0,2,0,1,"800.12"],
["another item",1,3,2,5,1,"1,713.59"],
(etc...)

I use the following code to explode the elements into an array.

<?php
$id = 0;
foreach($lines AS $line) {
  $id = 0;

  // remove brackets and line end comma's
  $found_data[] = str_replace(array('],', '[',']', '"'), array('','','',''), $line);

  // add data to array
  $results[$id] = explode(',', $line);

}

Which works fine for the first line, but as the second line uses a comma for the thousands seperator of the last item, it fails there. So somehow I need to disable the explode to replace stuff between " characters.

If all values would be surrounded by " characters, I could just use something like

explode('","', $line); 

However, unfortunately that's not the case here: some values are surrounded by ", some aren't (not always the same values are). So I'm a bit lost in how I should proceed. Anyone who can point me in the right direction?

Upvotes: 1

Views: 82

Answers (1)

anubhava
anubhava

Reputation: 785571

You can use json_decode here since your input string appears to be a valid json string.

$str = '["another item",1,3,2,5,1,"1,713.59"]'
$arr = json_decode($str);

You can then access individual indices from resulting array or print the whole array using:

print_r($arr);

Output:

Array
(
    [0] => another item
    [1] => 1
    [2] => 3
    [3] => 2
    [4] => 5
    [5] => 1
    [6] => 1,713.59
)

Upvotes: 4

Related Questions