dsshsta97935 2017-01-23 10:59
浏览 190
已采纳

php通过逗号爆炸忽略千位分隔符

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?

  • 写回答

1条回答 默认 最新

  • drl971115 2017-01-23 11:04
    关注

    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
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看