Dark Launch

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

PHP
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

PHP
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;
}

PHP
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;
}

Comments


  1. CR: Mac
    LF: Unix
    CRLF: Windows

  2. 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. Thank you

  4. 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. Nice one .)

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

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

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