Skip to content
← Back to Snippets
Code

Trim Whitespace from String

Trims whitespace from both ends of a string and also returns left-only and right-only examples.

Purpose

Trims whitespace from both ends of a string and also returns left-only and right-only examples.

Snippet details

ContextStringLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

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.
 */

/**
 * Trim Whitespace from String.
 *
 * Purpose:
 * Shows trim(), ltrim(), and rtrim() results for the same string.
 *
 * @param string $text Text containing possible whitespace.
 * @return array Trimmed text variants.
 */
function ogSnippetTrimWhitespace(string $text): array {
	return array(
		'original' => $text,
		'both' => trim($text),
		'left' => ltrim($text),
		'right' => rtrim($text)
	);
}

$trim_report = ogSnippetTrimWhitespace("  Pegasus recon log  \n");

echo 'Trimmed log: '.$trim_report['both'];