Comment system, how to convert Line Breaks?

Discussion in 'PHP' started by profs77, May 30, 2006.

  1. #1
    I'm trying to make a few things, lets say a comment system for example, I got it so that it filters out illegal html inputted by the user such as javascript or something. But if I enter a comment and skip a line, when I retrieve the comment or whatever from the database it gets all jumbled up. How do I convert line breaks to <br /> tags?
     
    profs77, May 30, 2006 IP
  2. tolra

    tolra Active Member

    Messages:
    515
    Likes Received:
    36
    Best Answers:
    1
    Trophy Points:
    80
    #2
    echo nl2br("test\ntest\n\ntest");
     
    tolra, May 30, 2006 IP
  3. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This is a variation on the problem of dealing with the problem with too many newlines in text. The following bit of PHP code should do the trick:

    
    $string = preg_replace("/[\r\n]+/", "<br />", $string); 
    
    Code (markup):
    This will work on mac, *nix and windows.
     
    clancey, May 30, 2006 IP
  4. mykoleary

    mykoleary Peon

    Messages:
    64
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    If you want to avoid the recently announced PCRE vulnerability, use str_replace instead. You do have to use several ("\r\n" "\r" "\n" in that order...) instead of just the one regexp. It all depends on what version of PHP/PCRE your host is using.
     
    mykoleary, Jun 2, 2006 IP
  5. Grokodile

    Grokodile Peon

    Messages:
    425
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Yeah, just to give a spelled out example...

    $x = str_replace("\r\n","\n",$x);
    $x = str_replace("\r","\n",$x);
    $x = str_replace("\n","<br>",$x);

    Just out of interest, this allows parsing of different OS text files with the same code after the first couple steps.
     
    Grokodile, Jun 3, 2006 IP