各OS向けにCSVを出力するときとか。
<?php
function convertEOL($string, $to = "\n")
{
return preg_replace("/\r\n|\r|\n/", $to, $string);
}
$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;
結果
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"