Reputation: 23
I am trying to run a csv export on a MySQL Database via PHP. Everything is working fine until I get to the description field. Where each line is terminated by new lines in the text field. So for every line in the text field, I get a new line in the CSV. When all I want is a new line for the end of the row.
I've tried a few solutions so far, including:
REPLACE(description, '\r\n', '\n')
str_replace( array( "\r" , "\n" ) ,'\n' , $data);
description = REPLACE(description, description, TRIM(BOTH '\r\n' FROM description))
Any help is appreciated.
Upvotes: 2
Views: 9186
Reputation: 5985
I usually use preg_replace()
preg_replace( "/\r|\n/", "", $data);
But you can always use str_replace() (it's faster)
str_replace(array("\r", "\n"), "", $data);
Upvotes: 1
Reputation: 7693
Why are you replacing it with \n
?
Try to replace it with an empty string instead, like ''
. Try to replace \r\n
with ""
and \n
with ""
Upvotes: 4
Reputation: 21
Newlines are not always \n
... they can be \r\n
, \n\r
, \n
and \r
depending on the character encoding.
If you have the ability to make a new csv data file and want to change the newlines to html br tags, check out the nl2br()
function, its really easy to use. If string replace does not work on the above newline characters, write the data to a temp file on the hard drive, then parse line by line to concatenate all newlines into a space. There are easy examples to follow in the PHP manual.
I actually had the opposite issue, where I had to go through a csv file that was already created and find the newlines. The answer in that case was using a regular expression, but I was fortunate in that the first and last columns of data were unique enough to parse and capture all the data in between. Another option would have been to remove all newlines and collect the data based on the number of columns.
Upvotes: 2
Reputation: 168685
You could try replacing with \\n
or even HTML <br>
tags. This will enable to you re-instate the line-breaks later on.
Upvotes: 0