Home > Software design >  trim function not working for string array
trim function not working for string array

Time:10-29

This is a really odd behavior that I can't explain. I have a CSV file that I'm trying to format. The lines could have trailing ','s that I want to remove.

$lines = explode(PHP_EOL, $csv);
$csv = '';
foreach($lines as $line) {
    $csv .= trim($line, ',') . PHP_EOL;
}

The trim is not doing anything and just returning the line back as it is. Just to make sure I copied a line from the csv trim("a,b,c,d,,", ','); which works fine. Can anyone tell me why the above code won't work?

CodePudding user response:

If the CSV file was created on a different operating system, it may use different line breaks than PHP_EOL. So trim any line break characters in addition to commas.

foreach($lines as $line) {
    $csv .= trim($line, ",\r\n") . PHP_EOL;
}

CodePudding user response:

Don't manually edit the CSV file. Parse it into an array, then edit the array. Then you can write the modified array back to a CSV file.

You can use fputcsv to write the data to a file, or str_putcsv (a custom function).

$newData = [];
$data = array_map('str_getcsv', $lines); // parse each line as a CSV

foreach ($data as $row) {
    $row = array_filter($row); // remove blank values

    // for some dumb reason, php has `str_getcsv` but not `str_putcsv`
    // so let's use `str_putcsv` from: https://gist.github.com/johanmeiring/2894568
    $newData[] = str_putcsv($row);
}

$newData = implode(PHP_EOL, $newData);
  •  Tags:  
  • php
  • Related