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

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:
Encapsulating the fields in quotation marks.
This:
$field = str_replace(array('\n', '\r', '\r\n', '\n\r'), ',', $original_field);
Also this:
$field = strip_tags(nl2br($original_field));
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?

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);

Use double quotes:
$field = str_replace(array("\n", "\r", "\r\n", "\n\r"), ',', $original_field);

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));

You have to put \n and similar tags in double quotes otherwise they will be treated as simple strings and not as linebreaks.

Related

Fixing weird indentation in text file with php

I'm taking this file and splitting it up into sentences. The issue is that its formatted weirdly. I need to remove all the random new lines, indentations and unneeded spaces. Is there a way to do this with php?
I am currently using
$test= file_get_contents("text.txt");
$stringtest = str_replace(PHP_EOL,'', $test);
But I am getting weird behavior when I try to split up the sentences. Is there a way to do this?
The weird behavior is that when I print out the text
echo $stringtest;
There are unseen characters between lines where a newline/weird_spacing used to exist.
You can use a regex to merge all whitespaces to a single space. Also you probably want to remove whitespace at the beginning and end. Try this:
$test = trim($test);
$test = preg_replace('/\s+/s', ' ', $test);

PHP: remove MySQL formatting such as line break and commas

I'm making a CSV file, one of the database filed has stored a section called comments/note which obviously have some commas and line breaks in it too. Looked around the web found usage of preg_replace(), not much familiar with regular expressions there fore combined two different ones and not getting anything in result its totally blank and i know all records have some sort of comments in it
this i used
preg_replace( "/\r|\n/|/[,]/", "", $string )
Please what do I need to do here get one text back without line breaks and commas
Regards
You can do it using strip_tags() and preg_replace();
$clean_str = trim(preg_replace('/\s\s+/', '', strip_tags($string)));
or try this
$clean_str = str_replace(array("\r\n","\r","\n", ","), '', strip_tags($string));

remove \n from paragraph

I have a jquery editable div that when you click on it you can edit the text. The problem is that when the data is called from the db and placed into the paragraph I keep getting a \n for every space. How can I replace the \n with an actual new line.
I tried nl2br(), but that's not very convenient for my users since they then have to play with the <br /> when they want to edit the paragraph.
Any thoughts?
What about:
str_replace("\\n", "", $str); // see if this gets rid of them
Then this should work to put actual newlines in there:
str_replace("\\n", "\n", $str); // should replace with actual newline
try:-
$strippedText = str_replace(chr(10), '', $textFromDB);
or
$strippedText = str_replace(chr(10), '<br/>', $textFromDB);
Does this work? (Working on the possiblity that the newlines are already escaped).
$strippedText = str_replace('\\n', ' ', $textFromDB);
Are you using a ready made solution or making your own? I use http://aloha-editor.org/ for stuff like this and it's mostly problem free.
Have you tried str_replace?
$myTextFromDB = str_replace('\n', PHP_EOL, $myTextFromDB);
Ok, I think this is different enough that I should do a separate answer for it.
Are you saying a literal "slash n" shows up on the page? Or are you saying that your newlines show up as spaces?
If it's the latter, then there's no way around that. HTML will show newlines only as a space - you have to convert to br tags to break the line if it's not in a textarea context. But you can always convert them back to newlines when you pop that textarea up for your user and this should work well for people.

How to remove new line (and some other) characters for csv output?

I have some data (which users input using WYSIWYG editor). I have created a tool to create a csv copy of the data for some backup purposes. For each record I
$csv_data .= str_replace(
array('<br />','<br/>', '\n', ','),
'',
strip_tags($db_data['description'])
).",";
for some of the records I find product description split across multiple lines, even though I am removing BR, new line characters etc above, and this breaks the csv file. Any idea what I am doing wrong? thank you very much for your help.
You use '' around the \n. Single Quotes do not allow escape characters like \n, use double quotes ("") instead.
See:
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single

Replacing text function in php

I want to clean up some parsed text such as
\n the said \r\n\r\n\r\n I look in your eyes my dear\r\n\r\nI see green rolling Forests\r\n\r\nI see the far away Sky\r\n\r\nThey turn into the rain\r\n\r\n\r\nI see high soaring eagles... more\n
So I want to get rid of the "\n", "\r\n", "\r\n\r\n", "\r\n\r\n\r\n", "\r\n\r\n\r\n\r\n" and "\r". That's all the combinations that appear in my parsed text.
Is there a way to do this in php?
If you just want 1 newline instead of multiple I would suggest this:
$clean = preg_replace(array("/\r+/","/(\n){2,}/"),array("","\n"),$text);
Otherwise str_replace to strip out newlines or nl2br will do the job. You could also adapt the regex to replace 1 or more newlines with a BR tag:
$clean = preg_replace(array("/\r+/","/\n+/"),array("","<br />"),$text);
What about
$text = str_replace(array("\n", "\r"), '', $text);
That will remove all new line characters.
If you want them as new lines, I'd change the replace to <br /> for HTML (or better still, use PHP's nl2br()), or standardise them in normal text with \n, for example.

Categories