使用 fgetcsv 替换数字中的逗号

Using fgetcsv to replace commans within numbers

提问人:Volatil3 提问时间:2/14/2023 更新时间:2/14/2023 访问量:34

问:

我有以下CSV数据:

"Symbol","Name","Trade Volume","Trade Value","UIN Settlement Volume ","UIN Settlement Value ","UIN Percentage Volume","UIN Percentage Value "
"786","786 INVESTMENT LIMITED","500.00"," 2,325.00 ","500.00"," 2,325.00 ","100.00 ","100.00 "
"ABL","ALLIED BANK LIMITED","15,501.00"," 981,819.00 ","10,001.00"," 629,379.00 ","64.52 ","64.10 "
"ABOT","ABBOTT LABORATORIES (PAKISTAN) LIMITED","4,043.00"," 1,730,197.34 ","3,031.00"," 1,299,214.65 ","74.97 ","75.09 "
"ACPL","ATTOCK CEMENT PAKISTAN LIMITED","40,231.00"," 2,345,598.00 ","36,131.00"," 2,107,058.00 ","89.81 ","89.83 "
"ADAMS","ADAM SUGAR MILLS LIMITED","4,091.00"," 107,544.61 ","3,091.00"," 80,669.61 ","75.56 ","75.01 "

在使用 拆分 w.r.t 逗号之前,我想从数字中删除命令。我该怎么做?fgetcsv

我当前的代码如下所示:

while (($row = fgetcsv($file, 1000, ",")) !== FALSE) {
            print("<br><b>Before</b><br>");
            print_r($row);
            $row = preg_replace('/([0-9]+),([0-9]+)/', '$1$2', $row);
            // $row = preg_replace('/"([0-9]+),([0-9]+)(.*?)"/', '"$1$2$3"', $row);
            print("<br><b>After</b><br>");
            print_r($row);
            $Symbol = $row[0];
php fgetcsv

评论

0赞 Alex Howansky 2/14/2023
为什么要在fgetcsv()之前这样做?fgetcsv() 将正确解析值,因为它们被引用,并且去除后面的逗号要容易得多(只需 str_replace())并且不太可能中断。
0赞 Volatil3 2/14/2023
@AlexHowansky 该值仅存储为。2,325.002
0赞 Volatil3 2/14/2023
@AlexHowansky我的意思是不使用preg_replace,如果我使用preg_replace则上述结果仅第一个值有效,否则无效
0赞 Alex Howansky 2/14/2023
你不需要去掉这些逗号,因为 fgetcsv() 不会在带引号的字符串内的逗号上换行。在调用 preg_replace() 之前发布输出,您将在那里看到值。print_r($row);2,325.00
0赞 Volatil3 2/14/2023
@AlexHowansky我遇到了问题,是mysql数据类型截断了它double

答:

0赞 Dimitry 2/14/2023 #1

是否要从所有单元格中的数字中删除多余的逗号和空格?

fgetcsv 的结果是一个数组,而不是一个字符串。您需要处理每个项目

while (($row = fgetcsv($file, 1000, ",", "\"")) !== FALSE) {
    echo "<br><b>Before</b><br>" . PHP_EOL;
    print_r($row);
    $row = array_map(function($el) {
            if (preg_match("/^[. ,0-9]+$/", $el)) {
                $el = preg_replace("/,/", "", trim($el));
           }
           return $el;
        },
        $row);
    echo "<br><b>After</b><br>" . PHP_EOL;
    print_r($row);
    $Symbol = $row[0];
}