tanger has asked for the wisdom of the Perl Monks concerning the following question:

hey all~!

I wish to insert comments inside a mysql database column which is a varchar(255) type. I'm not sure where to look to solve my problem, I even tried using some modules like Text::Wrap, but that doens't help much with this.

My problem is not when I insert a comment. For example, if the comment typed out on the textarea field looks like this:
This is a sample comment being inserted into a MySQL DB. I would like + to format things correctly when being edited. This is the 2nd "paragraph", or sentence after the line above this one +.
Now when I insert it, the format is fine. But lets say I try to edit this comment, and I add the word "Hello" at the very end, then the comment will look like this:
This is a sample comment being inserted into a MySQL DB. I would like + to format things correctly when being edited. This is the 2nd "paragraph", or sentence after the line above this one +. Hello
Notice how it adds two whole new line breaks between the first one? How do I remove that extra space? What is causing it too add those new lines?

I want to allow new lines to indicate a new paragraph, so I don't want to do a regex that removes all \n's ?

Is there anyway I can solve this with a perl regex?

thank you!

Replies are listed 'Best First'.
Re: Formatting a Textarea field
by TedPride (Priest) on Jun 05, 2005 at 22:19 UTC
    The problem is likely that the original comment contained both a carriage return and a line break, and when you go to put the comment back in the textarea, both are interpreted as line breaks in your browser.

    Just remove all carriage returns from the text before submitting it to the database, and you should be fine.

    EDIT: Something like the following, perhaps, though I imagine someone will come up with a better regex.

    $text =~ s/(?:\r\n|\n\r)/\n/g;
      TedPride's reply is right on the money, IMO, but I'd simply delete the CR (="\r") characters, leaving every actual LF (="\n") characters intact:
      $text =~ tr/\r//d;
Re: Formatting a Textarea field
by davidrw (Prior) on Jun 05, 2005 at 22:00 UTC
    Yes, you can solve with a regex, but it is probably much better to have us help you fix the root cause -- to help us do that, can you post some code?

    As for the regex, the concept is simply to replace double breaks with a single one, instead of removing all of them: s/\n\n/\n/sg
    Or (depending on the desired behavior) you could do: s/\n\n+/\n/sg
      hey, thanks for the replies all of you.

      Tep was right on the money with this, but I used the regex bart gave me becaues it seems more fit. :) Thanks you guys are great.

      tanger