php 逗号爆炸忽略千位分隔符
php explode by comma ignore thousands seperator
我正在从无法更改的外部资源中抓取以下类型的字符串:
["one item",0,0,2,0,1,"800.12"],
["another item",1,3,2,5,1,"1,713.59"],
(etc...)
我使用以下代码将元素分解为一个数组。
<?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);
}
第一行工作正常,但由于第二行对最后一项的千位分隔符使用逗号,因此它在那里失败。所以我需要以某种方式禁用爆炸以替换 " 字符之间的内容。
如果所有值都被 " 字符包围,我可以只使用
explode('","', $line);
然而,不幸的是,这里的情况并非如此:有些值被 " 包围,有些则不是(不总是相同的值)。所以我对应该如何进行有点迷茫。任何人都可以给我指出正确的方向?
您可以在此处使用 json_decode
,因为您输入的字符串似乎是有效的 json 字符串。
$str = '["another item",1,3,2,5,1,"1,713.59"]'
$arr = json_decode($str);
然后您可以访问结果数组中的各个索引或使用以下方法打印整个数组:
print_r($arr);
输出:
Array
(
[0] => another item
[1] => 1
[2] => 3
[3] => 2
[4] => 5
[5] => 1
[6] => 1,713.59
)
我正在从无法更改的外部资源中抓取以下类型的字符串:
["one item",0,0,2,0,1,"800.12"],
["another item",1,3,2,5,1,"1,713.59"],
(etc...)
我使用以下代码将元素分解为一个数组。
<?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);
}
第一行工作正常,但由于第二行对最后一项的千位分隔符使用逗号,因此它在那里失败。所以我需要以某种方式禁用爆炸以替换 " 字符之间的内容。
如果所有值都被 " 字符包围,我可以只使用
explode('","', $line);
然而,不幸的是,这里的情况并非如此:有些值被 " 包围,有些则不是(不总是相同的值)。所以我对应该如何进行有点迷茫。任何人都可以给我指出正确的方向?
您可以在此处使用 json_decode
,因为您输入的字符串似乎是有效的 json 字符串。
$str = '["another item",1,3,2,5,1,"1,713.59"]'
$arr = json_decode($str);
然后您可以访问结果数组中的各个索引或使用以下方法打印整个数组:
print_r($arr);
输出:
Array
(
[0] => another item
[1] => 1
[2] => 3
[3] => 2
[4] => 5
[5] => 1
[6] => 1,713.59
)