in reply to converting carriage returns to <br> tags (was: Simple Question for you guys)

As I learned when I posted a similar question, the textarea is likely to be giving you newlines and returns if the client is PC. So you might want something like:
$textarea =~ s|[\r\n]|<br />|g;
Note: not sure if it's \r\n or \n\r.

Replies are listed 'Best First'.
Re: Re: Simple Question for you guys.
by chipmunk (Parson) on May 18, 2001 at 23:05 UTC
    If the textarea is returned with \r\n line endings, then that substitution will insert two <BR /> tags at the end of each line.

    I prefer something like this: $textarea =~ s,\r\n?|\n\r?,<br />\n,g; I like to keep a newline after the BR tag, to make the HTML easier to read.

Re: Re: Simple Question for you guys.
by AidanLee (Chaplain) on May 18, 2001 at 20:40 UTC
    A good suggestion for getting the job done right (which I'm always a fan of), but it doesn't hurt to note that the browser will display things okay without converting both. As long as a <br /> tag is there.
      True. What caused me pain was wanting to convert two newlines to two BR tags, but leave single newlines alone.

      Trying to match on \n\n was not working because what was there was really \n\r\n\r.

Re: Re: Simple Question for you guys.
by Buckaroo Buddha (Scribe) on May 18, 2001 at 21:16 UTC
    why are you using
    s|[\r\n]|<br />|g;
    instead of
    s/[\r\n]/\<br \>/g;

    are the pipes somehow more efficient in this case or just more readable?

    the other thing i'm wondering about is the square brackets... does that mean  /[asdf\.]/ would search for each of those characters (a, s , d, f and Period) versus the string 'asdf.'

    i know they're silly questions but i'm trying to get back up to speed with reading perl ... after about 8 months in visual basic for applications

    there were so many REALLY nice things about working in VBA ... for example the editor will automatically fill display a list of the sub objects and methods of the object that you're working with... but then again the number of times i've struggled with the long way around a hash table or an array makes me really glad to be back in PerlScript (with a bit of Win32::OLE)

    anyways ... i'm rambling :)

      You can choose your own delimiters. Anytime there's forward or back slashes in the reg exp, it' better to use a different delimitter. "Slanted toothpicks" or something is the name for the syndrome to avoid.

      pipes are no more efficient as regex delimiters. You have it exactly right on your latter guess though, it's a whole lot more readable than

      s/[\r\n]/<br \/>/g;

      You've also guessed right about the brackets. It's a way to specify a group of characters to match without specifying what order they appear in.