Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I strip all line breaks to generate a proper CSV?

Tags:

php

csv

I have a textarea submitting to my database on a website that is properly working. But when I generate a CSV (via PHP) from my database, all line breaks will mess up with the resulting CSV. Any CSV reader will interpret the line break from the input into a new line.

I have tried the following approaches:

  1. Encapsulating the fields in quotation marks.

  2. This:

    $field = str_replace(array('\n', '\r', '\r\n', '\n\r'), ',', $original_field);
    
  3. Also this:

    $field = strip_tags(nl2br($original_field));
    
  4. Combining all approaches above.

Anyhow, the ending result will still be a messed up CSV that will break on any line break inputted by user. I have managed to block new line breaks from the text area, but there's a lot of legacy submissions that need me to fix this on the CSV side as well.

Why is it not working? How can I fix this issue?

like image 375
Gus Fune Avatar asked Oct 31 '12 13:10

Gus Fune


People also ask

How do I remove a line break in CSV?

Press and hold the Alt key and then enter “010” from your keyboard's 10-keypad part.

How do I remove a line break in Excel csv?

Place the cursor in the 'Find what' field and use the keyboard shortcut – Control + J (hold the Control key and press the J key). You may not see anything, but this puts the line break character in the 'Find what' field. In the replace field, enter a comma followed by a space character (, ) Click on Replace All.

What causes line breaks in CSV?

By default, when you export to CSV files, fields that have multiple lines of text, such as description fields, will be collapsed to a single line of text. This is because such line breaks may cause problems when you import into another application, such as Excel.

Can you have line breaks in CSV?

In CSV linebreaks are used to separate individual rows, so a linebreak inside a cell may cause problems.


2 Answers

Before accepted answer (of user user1517891) is not correct, it will replace in string twice, when there is \r\n... It will replace it as two commas ,. First it will replace \r => ,, then \n => ,.

You need to use it in different order, as:

$field = str_replace(array("\r\n", "\n\r", "\n", "\r"), ',', $original_field);
like image 123
Legionar Avatar answered Oct 21 '22 15:10

Legionar


I'd suggest using preg_replace() for this rather than str_replace(). The reason is that there may be multiple newlines and combinations of \r and \n, and I would expect that you'd want to replace them all with just a single comma.

I'd also suggest using trim() to remove trailing blank lines.

$field = preg_replace('/[\n\r]+/', ',', trim($original_field));
like image 36
SDC Avatar answered Oct 21 '22 14:10

SDC