104
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Posted at

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
104
98

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?