从CSV数据字符串中删除换行符(PHP 5.3之前)

时间:2014-04-01 11:01:16

标签: php csv

我有一个包含CSV文件内容的大字符串。到目前为止,我并不关心解析它,因为我的程序只是将它从一个源流式传输到另一个源。

您的任务,如果您决定接受它,就是告诉我从包含多个CSV数据行的字符串的数据元素中删除换行符的最佳方法,而不会丢弃分隔行本身的换行符。数据被正确引用,实现必须在PHP 5.2上运行......

id,data,other
1,"This is data
with a line break I want replacing",1
2,"This is a line with no line break in the data",0
3,No quotes,42
4,"Quoted field with ""quotes inside"" which is tricky",84

1 个答案:

答案 0 :(得分:1)

我认为,如果CSV数据中存在换行符,则该行上必须有一个奇数(不成对)的引号。如果存在这样的行,则删除其换行符并检查新创建的行是否有效。 以下伪PHP代码应该可以工作。事物行ReadercontainsOddNumberOfQuotes()在PHP 5.2中很容易实现:

function fixCsv($fileOrString) {
    $reader = new Reader($fileOrString);
    $correctCsv = "";
    while ($reader->hasMoreLines()) {
        $correctCsv = $correctCsv . fixLine($reader, $reader->readLine()) . "\n";
    }
    return $correctCsv;
}

/** Recursive function that returns a valid CSV line. */
function fixLine($reader, $line) {
    if (containsOddNumberOfQuotes($line)) {
        if ($reader->hasMoreLines()) {
            // Try to make a valid CSV line by joining this line with the next one.
            return fixLine($reader, line . $reader->readLine())
        }
        throw new Exception("Last line is incomplete.");
    }
    else {
        return $line;
    }
}