duanmu6231 2011-04-20 22:19
浏览 66
已采纳

修改空白的PHP fgetcsv错误的任何变通方法?

Given the following string of CSV data (I am unable to ensure the fields are quoted)

AB,CD,   EF,GH,   IJ

and PHP code of:

$arr = fgetcsv($f);

(assuming $f is a valid file-pointer reading a file containing the above text) - one would expect this result:

Array('AB', 'CD', '   EF', 'GH', '   IJ');

when in fact you get:

Array('AB', 'CD', 'EF', 'GH', 'IJ');

This is problematic if you need positional context within that field.

Any workarounds of still being able to take advantage of fgetcsv, but ensuring that whitespace is not lost?

The bug is reported here: http://bugs.php.net/bug.php?id=53848

  • 写回答

1条回答 默认 最新

  • duaabhuv188411 2011-04-20 22:58
    关注

    Oooops. S**t.
    I accidently already wrote a function which doesn't strip the spaces:

    function str_getcsv2($line, $del=",", $q='"', $esc="\\") {
        $line = rtrim($line, "
    ");
        preg_match_all("/\G ([^$q$del]*) $del | $q(( [$esc$esc][$q]|[^$q]* )+)$q $del /xms", "$line,", $r);
        foreach ($r[1] as $i=>$v) {  // merge both captures
            if (empty($v) && strlen($r[2][$i])) {
                $r[1][$i] = str_replace("$esc$q", "$q", $r[2][$i]);  // remove escape character
            }
        }
        return($r[1]);
    }
    

    Use it like:

    $arr = str_getcsv2(fgets($f));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?