Removing newlines when writing to text file in php - php

I'm trying to store user messages from a textarea, into a text file, along with the user's name and date(though lets ignore the date for now).
Lets say the the user, named John, enters the following text into the textarea:
Hello
How are you?
I want the text file to store this as:
John#Hello\nHow are you?
I have tried many ways to remove/replace the newline from the textarea, but the result I get in the text file always looks like this:
John#Hello
How are you?
I just can't make it not go to the next line in the file. I've tried searching and haven't seen anyone having this problem...so perhaps I don't know what I'm doing. Anyone have a solution?

To replace the newline with a literal \n, use str_replace and put \n in single quotes so it's not interpreted as an escape sequence.
$text = str_replace("\n", '\n', $text);
file_put_contents("filename.txt", "$username#$text");
What is the difference between single-quoted and double-quoted strings in PHP?
Alternatively, you could escape the backslash: "\\n"

Use preg_replace("#[\n\r]+#", '\\n', $text);

Related

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 use nl2br() to handle string with '\r\n'?

I am retrieving a product description value stored in database from admin through textarea upon form submit. When I select the description from database I get $description = $row['description']; and I would like to echo $description on main page like this: echo nl2br($description); but I see "\r\n" characters instead of making new rows. From what I've found here and on the net, your string must be used between double quotes, like this:
echo nl2br("Hello, \r\n This is the description");
Now, the value of $description from database is in fact "Hello, \r\n This is the description" but in my script I have to use it like this:
echo nl2br($description);
Which does not make br's, it is outputing \r\n instead. So, what can I do, I can't use double quotes here, from my experience.
You could translate them into their respective escape sequences before passing the string through nl2br(), like this:
$description = nl2br(str_replace('\\r\\n', "\r\n", $description));
But what are the literal escapes doing in your database in the first place?
You are storing the literal value of \r\n in your database, not the actual characters they represent.
Verify this in your database. If you see \r\n in the description field, then you're probably escaping the backslash when you're storing the data.
It looks like your text contains the individual characters \, r, \, and n, and does not contain actual newline characters. As such, str_replace() should get the job done:
echo str_replace('\r\n', '<br>', $description);
The nl2br can take a second (optional) argument for "is_xhtml" which will convert the \r\n into a <br> for you. Just change your line to:
echo nl2br($description, TRUE);

Can't see new lines on textarea - what could the problem be?

I have a php string with a lot of information to be displayed inside a textarea html element.
I don't have access to that textarea nor to the script (if any) that generates it.
$somestring = 'first line \nSecond line \nThird line.';
$somestring as NOT been "worked" with trim or filter_var. Nothing.
On the textfield, I get the \n printed on the textarea hence, not interpreted.
What can I try in order to have those new lines applied?
Thanks in advance.
Try wrapping $somestring with " (double quotes) instead of ' (single quotes)
\n, \r and other backslash escape characters only works in double quotes and heredoc. In single quotes and nowdoc (the single quote version of heredoc), they are read as literal \n and \r.
Example:
<?php
echo "Hello\nWorld"; // Two lines: 'Hello' and 'World'
echo 'Hello\nWorld'; // One line: literally 'Hello\nWorld'
echo <<<HEREDOC
Hello\nWorld
HEREDOC; // Same as "Hello\nWorld"
echo <<<'NOWDOC'
Hello\nWorld
NOWDOC; // Same as 'Hello\nWorld' - only works in PHP 5.3.0+
Read more about this behaviour in the PHP manual
EDIT:
The reason single and double quotes behave differently is because they are both needed in different situations.
For instance, if you would have a string with a lot of new lines, you would use double quotes:
echo "This\nstring\nhas\na\nlot\nof\nlines\n";
But if you would use a string with a lot of backslashes, such as a file name (on Windows) or a regular expression, you would use single quotes to simplify it and avoid having unexpected problems by forgetting to escape a backslash:
echo "C:\this\will\not\work"; // Prints a tab instead of \t and a newline instead of \n
echo 'C:\this\would\work'; // Prints the expected string
echo '/regular expression/'; // Best way to write a regular expression
$somestring = "first line \nSecond line \nThird line.";
http://php.net/types.string <-- extremely useful reading
this article is a cornerstone of PHP knowledge and it's just impossible to use PHP without it.
unlike most of manual pages which are are just for quick reference, this very page is one which every developer should learn by heart.

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

How can I make this string from a 'textarea' to be on one single line?

I have tried and tried and tried now.
I have a mysql field (TEXT) which contains the value of a textarea.
That is, if the text is written EXACTLY like this:
Hello. Hello.
Hello.
Hel
lo.
Then thats how it will appear in the mysql field because Im using wordwrap and nl2br functions when inserting it there.
Now, I am creating a dynamic page, where the 'meta description content' is updated with the 'TEXT' content, BUT, in one long string without any breaks and new lines.
That said, I need to make text to be in one string.
I have used this:
str_replace ("<br/>", "", $string);
This displays the text as one string, yes, but when viewing the source code of the page, you can see that the breaks are there, like this:
<meta name="description" content="
Hello. Hello.
Hello.
Hel
lo." />
I have also tried replacing the with '\n' and others, without success...
How can I solve this irritating problem?
Let me know if you need more input, and I will update this Q.
Replace all groups of whitespace with a single space:
$output = preg_replace('!\s+!', ' ', $input);
Try replacing "\n" with "" instead.
handy function:
function removeEmptyLines($s) {
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $s);
}
You might try to something like this str_replace("\n\r", "", $string); I have found that sometimes the return character \r is hiding in there someplace.

Categories