Removing Too Many Newlines and Linux

Discussion in 'PHP' started by Shadow, Apr 20, 2006.

  1. #1
    This is a piece of code that will replace an unknown number of newlines with just one newline.

    
    preg_replace("/(\r\n)+/", "\r\n", $string)
    
    PHP:
    Yes, this works fine on Windows, but it doesn't work on Linux. AFAIK Windows uses /r/n and Linux uses /n only.

    Does anyone know how to make it work on Windows and on Linux? Besides checking what OS the user is using before sending the $string. Or is that the only way?
     
    Shadow, Apr 20, 2006 IP
  2. hansi

    hansi Peon

    Messages:
    129
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    As PHP is server side i think you only have to check what OS is running the server and then choose \r\n or \n.
     
    hansi, Apr 20, 2006 IP
  3. clancey

    clancey Peon

    Messages:
    1,099
    Likes Received:
    63
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    $string = preg_replace("/[\r\n]+/", "\n", $string);
    
    PHP:
    This worked for me on both Windows and Linux because it was looking for multiple instances of "\r" and/or "\n" characters and replacing them with a single "\n"

    Replacing with a single "\n" gives the expected result in both Windows and Linux versions of PHP.
     
    clancey, Apr 20, 2006 IP
    Shadow likes this.
  4. Shadow

    Shadow Peon

    Messages:
    191
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yes, great, thanks a bunch
     
    Shadow, Apr 20, 2006 IP