开发者

Any workarounds for the PHP fgetcsv bug where whitespace is trimmed?

开发者 https://www.devze.com 2023-02-27 22:10 出处:网络
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:

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 worka开发者_运维百科rounds 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


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, "\r\n");
    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));
0

精彩评论

暂无评论...
验证码 换一张
取 消