Skip to content
← Back to Functions
Code

Normalize Line Endings

Converts mixed line endings to a selected standard without altering text content.

Function signature

ogNormalizeLineEndings(text, target = 'lf', preserve_final_newline = true)

Categories

  • Content Display

Parameters

textSource text.targetTarget newline mode or sequence.preserve_final_newlineWhether to preserve a final trailing newline.

Return value

Short public-safe status message.

  • text
  • newline
  • had_final_newline

Compatibility

Existing function name and call order preserved; metadata signature corrected to source.

Minimum PHP version: 7.4

Security notes

Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Normalizes mixed line endings to one selected newline sequence.
 *
 * Approved target values are lf, crlf, cr, or a literal newline sequence.
 *
 * @param string $text Source text.
 * @param string $target Target newline mode or sequence.
 * @param bool $preserve_final_newline Whether to preserve a final trailing newline.
 * @return array Structured result with normalized text.
 */
function ogNormalizeLineEndings($text, $target = 'lf', $preserve_final_newline = true) {
	$result = array(
		'success' => false,
		'message' => '',
		'data' => array()
	);

	$text = (string)$text;
	$target = (string)$target;
	$had_final_newline = false;
	if (preg_match('/(\r\n|\n|\r)$/', $text)) {
		$had_final_newline = true;
	}

	if ($target == 'crlf') {
		$newline = "\r\n";
	} elseif ($target == 'cr') {
		$newline = "\r";
	} elseif ($target == 'lf') {
		$newline = "\n";
	} else {
		$newline = $target;
	}

	if ($newline !== "\n" && $newline !== "\r\n" && $newline !== "\r") {
		$result['message'] = 'Invalid target newline.';
		return $result;
	}

	$normalized = str_replace(array("\r\n", "\r", "\n"), "\n", $text);
	$normalized = str_replace("\n", $newline, $normalized);

	if (!$preserve_final_newline && $had_final_newline) {
		$normalized = rtrim($normalized, "\r\n");
	}

	$result['success'] = true;
	$result['message'] = 'Line endings normalized.';
	$result['data'] = array(
		'text' => $normalized,
		'newline' => $target,
		'had_final_newline' => $had_final_newline
	);

	return $result;
}