PHP

PHPで改行コードを統一する関数: CRLF, CR, LF が混在してる文字列を LF に変換するなど

More than 1 year has passed since last update.

各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"