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

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
// Normalize line endings.
function normalize($s) {
    // Convert all line-endings to UNIX format.
    $s = str_replace(array("\r\n", "\r", "\n"), "\n", $s);
 
    // Don't allow out-of-control blank lines.
    $s = preg_replace("/\n{3,}/", "\n\n", $s);
    return $s;
}
Did this help you? Please let me know with a comment. Thank you
Posted .

7 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);

Leave a comment