Remove line breaks from CSV data line (pre PHP 5.3)

I have a large line containing the contents of a CSV file. Until now, I did not care about its parsing, as my program simply broadcast it from one source to another.

Your mission, if you decide to accept it, is to tell me the best way to remove line breaks from data elements of a string containing multiple CSV data lines, without dropping line breaks separating the lines themselves. The data is correctly quoted, and the implementation should run in 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
+4
source share
1 answer

, CSV- , () . , , . -PHP . Reader containsOddNumberOfQuotes() 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;
    }
}
+1

Source: https://habr.com/ru/post/1534421/


All Articles