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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog