suin.io

PHP Normalize newlines; for example, convert all CRLF, CR, and LF to LF

suinAugust 1, 2016

This very simple PHP function normalizes and converts newline characters to CRLF, CR or LF.

PHP
function convertEOL($string, $to = "\n")
{   
    return preg_replace("/\r\n|\r|\n/", $to, $string);
}

Here's a test code showing how the function works:

Test
$string = "CR + LF: \r\n CR: \r LF: \n";

echo "Testing string:", PHP_EOL;
echo json_encode($string), PHP_EOL;

echo "For MacOSX, Unix, Linux", PHP_EOL;
echo json_encode(convertEOL($string)), PHP_EOL;

echo "For Windows", PHP_EOL;
echo json_encode(convertEOL($string, "\r\n")), PHP_EOL;

echo "For MacOS 9", PHP_EOL;
echo json_encode(convertEOL($string, "\r")), PHP_EOL;

The result will be like:

Testing string:
"CR + LF: \r\n CR: \r LF: \n"
For MacOSX, Unix, Linux
"CR + LF: \n CR: \n LF: \n"
For Windows
"CR + LF: \r\n CR: \r\n LF: \r\n"
For MacOS 9
"CR + LF: \r CR: \r LF: \r"