views:

100

answers:

2

I have a text area in HTML where the user can enter text, but when the form is submitted, and its passed to a php script which echo's it, there aren't any newlines. Knowing that HTML does that, I tried doing a preg_replace() before echoing it...

    echo preg_replace("/\n/", "<br />", $_GET["text"]);

but still everything is on one line.

So my best guess is that HTML textareas use a different newline character... can anybody shed some light on the subject?

EDIT

Ok, so I've figured out the problem: The Javascript is stripping the newlines. view code here

EDIT 2

Ok, so thanks to Jason for solving this problem. I needed to do:

    escape(document.getElementById('text'));

Instead of just:

    document.getElementById('text');

and the newlines are preserved, problem solved!

+1  A: 
echo nl2br($_GET['text'])

Though, your preg_replace worked for me!

Jason
Still no luck...
TheAdamGaskins
Really?! Both methods are working for me?
Jason
When you view-source, are you printing a new line? As in, after you submit the form, `echo $_GET['text']` what do you see in the actual, unformatted HTML?
Jason
If I just directly `echo $_GET['text']`, I get everything all on one line... strange...
TheAdamGaskins
What are you getting in your query string? I get `%0D%0A` in place of `\n` in my QS (`+` in place of a space).
Jason
My query string just comes across as `asdfasdf`, when I put a newline between the asdfs in the form... Here's the code: http://pastebin.com/raw.php?i=w79aMvSv
TheAdamGaskins
I'm using Javascript to load the page in with the get parameter set to the contents of the input textarea, so that way I enter new text and watch it update instantly.
TheAdamGaskins
So i think the Javascript is scraping the newlines out
TheAdamGaskins
try : `escape(document.getElementById('text').value)` That should work.
Jason
Works perfectly! Thanks!
TheAdamGaskins
Uh oh, that's bad. You should be using `nl2br(htmlspecialchars($_GET['text']))`
kijin
Good point; I wouldn't have thought of that. Thanks!
TheAdamGaskins
actually `nl2br(htmlspecialchars(stripslashes($_GET['text'])))`.
Jason
A: 

usually when testing for newlines in any string, I use /[\n\r]/, just to cover my bases. My guess is that this would match the new lines.

Jesse
Doesn't seem to work...
TheAdamGaskins
you might have some odd encoding, or possibly the breaks are being stripped out before you get the GET data? That regex will match any line break, I use it for a webapp right now (well, actually I use `'/([^\n\r]+)[\n\r]/'`, but it's essentially the same thing.
Jesse
I'm wondering if you are getting your breaks, stripped out also.
Jason
That appears to be what's happening... I'm primarily calling the page via Javascript... I'll pastebin the code
TheAdamGaskins