Jump to content

Textarea Linebreaks and MySQL


skubasteve

Recommended Posts

Hi everyone,

 

I'm driving myself crazy with this easy-to-fix problem that for some reason I cannot figure out.

 

I have a script where the data from a textarea is inserted into MySQL.  For some reason, I cannot prevent MySQL from adding the linebreaks from the text area into the database.  Ideally I want the text inside the textarea to be inserted as one single line (not multiple lines with spaces between them).

 

For example I want the text:

line 1

line 2

line 3

 

to be inserted into the database as:

line 1<br><br>line 2<br><br>line3

 

I've tried everything I can think of including str_replace, trim, stripslashes, etc.

 

nl2br() doesn't work either.  When i use nl2br() the end result in the database is:

line 1<br>
<br>
line 2<br>
<br>
line 3

 

Anyone have the solution to getting this text submitted into a database as a single line?

Link to comment
https://forums.phpfreaks.com/topic/197641-textarea-linebreaks-and-mysql/
Share on other sites

$text = str_replace("\n", "", nl2br($text));

 

Should work for what you want.

 

Thanks for the help, unfortunately here's what the output was when I tried your suggestion:

 

line 1<br />
<br />
line 2<br />
<br />
line 3

 

I would store it in the database in the raw format, but I'm have another script which reads the database entries and won't work if there's a line break.

This seems to do what you want. There may be a better way, but I can't think of it off the top of my head . . .

$text = "this\n is a \n test\n file with \n linebreaks.";
$insert_data = strip_tags(nl2br($text));
echo $insert_data;
// echo result is: this is a test file with linebreaks.

$text = "this\n is a \n test\n file with \n linebreaks.";

$insert_data = strip_tags(nl2br($text));

echo $insert_data;

// echo result is: this is a test file with linebreaks.

 

I tried that, but it somehow still preserved the linebreaks.

 

Anyway, I just figured it out.  Here's what you have to do to get entries from textareas submitted without linebreaks, while preserving the breaks for future use.

 

$text = nl2br($text);
$text = str_replace("\r", "", $text);
$text = str_replace("\n", "", $text);

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.