-1

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
emilkof
  • 13
  • 1
  • 1
    `John#Hello\nHow are you?` will always produce a new line when writing to a file with the `\n`. Are you asking to store `\n` as 2 characters? If so, use single quotes. Show your code. – Funk Forty Niner Nov 11 '15 at 22:18
  • do you want a literal backslash and `n` in the file? – Barmar Nov 11 '15 at 22:19
  • 1
    `$var = "John#Hello\nHow are you?";` will store a new line. Do `$var = 'John#Hello\nHow are you?';` will store as a string literal. Even harder to give a concrete answer without seeing code. – Funk Forty Niner Nov 11 '15 at 22:21

2 Answers2

5

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"

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Wishing you well on this one. Looks good to me, but I fear the OP'll just come back and say "It doesn't work...". (I could be wrong though) Hoping for a green tick here and that you're not in for a long haul. ;-) – Funk Forty Niner Nov 11 '15 at 22:23
  • Thanks Barmar, that worked for me. I wasn't aware that it mattered if I used "\n" or '\n'. – emilkof Nov 11 '15 at 23:12
  • I've added a link to a question that explains all the differences between single and double quoted strings. – Barmar Nov 11 '15 at 23:14
-1

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

Dracony
  • 842
  • 6
  • 15