Skip to main content

A PHP function to convert newline characters to UNIX (by default) or Windows and collapse lines containing two or more adjacent empty lines, into one empty line.

/**
 * Normalize Lines
 *
 * Normalize and convert newline characters to UNIX (by default) or
 * Windows and collapse lines containing two or more adjacent empty lines
 * into one empty line.
 *
 * @param  string  $str     The string of lines to normalize.
 * @param  boolean $windows Set as `true` to convert line endings to
 *                          Windows. The default value is `false`, and  
 *                          UNIX line endings will be used.
 *
 * @return string The normalized lines.
 */
function normalizeLines($str, $windows = false) {
	$str = str_replace("\r\n", "\n", $str);
	$str = str_replace("\r", "\n", $str);
	$str = preg_replace("/\n{2,}/", "\n\n", $str);

	if ($windows === true) {
		$str = str_replace("\n", "\r\n", $str);
	}
	
	return $str;
}