Jump to content

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

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.