PHP Normalize Newlines/Line Endings; CRLF; CR; LF; UNIX, Windows, Mac

Content

define('CR', "\r");         // Carriage Return: Mac define('LF', "\n");         // Line Feed: Unix define('CRLF', "\r\n");     // Carriage Return and Line Feed: Windows define('BR', '<br />' . LF); // HTML Break function normalize($s) {     // Normalize line endings using Global     // Convert all line-endings to UNIX format     $s = str_replace(CRLF, LF, $s);     $s = str_replace(CR, LF, $s);     // Don't allow out-of-control blank lines     $s = preg_replace("/\n{2,}/", LF . LF, $s);     return $s; } function normalize($s) {     // Normalize line endings     // Convert all line-endings to UNIX format     $s = str_replace("\r\n", "\n", $s);     $s = str_replace("\r", "\n", $s);     // Don't allow out-of-control blank lines     $s = preg_replace("/\n{2,}/", "\n\n", $s);     return $s; }
Posted . Did this help you? Please let me know with a comment. Thank you

Comments (RSS)

  1. anonymous

    CR: Mac

    LF: Unix

    CRLF: Windows

  2. anonymous

    LF:    Line Feed, U+000A

    VT:    Vertical Tab, U+000B

    FF:    Form Feed, U+000C

    CR:    Carriage Return, U+000D

    CR+LF: CR (U+000D) followed by LF (U+000A)

    NEL: Next Line, U+0085

    LS:    Line Separator, U+2028

    PS:    Paragraph Separator, U+2029

  3. anonymous

    Thank you

  4. anonymous

    I had a problem reading text from a mysqul database in order to create a shell script... But the scrip came out with line break in different format and could not be executed properly. So I use your script to convert text from database... AND IT WORKS fine. Thanks a lot

  5. anonymous

    Nice one .)

  6. anonymous

    Use "/\n{3,}/" instead of "/\n{2,}/" for the regex. It is pointless to replace "\n\n" with "\n\n".

  7. anonymous

    $s = str_replace("\r\n", "\n", $s);

        $s = str_replace("\r", "\n", $s);

    ???

        $s = str_replace(["\r\n", "\n"], "\n", $s);