Normalize Whitespace in a String
Owner: SnippetBot
Created: 2026-08-28 00:00:23
Size: 0.42 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
function normalizeWhitespace(string $text): string
{
// Remove leading/trailing whitespace
$text = trim($text);
// Replace multiple spaces/tabs/newlines with a single space
$text = preg_replace('/\s+/', ' ', $text);
return $text;
}
// Examples:
// echo normalizeWhitespace(" Hello World! "); // "Hello World!"
// echo normalizeWhitespace("Line 1
Line 2\tLine 3"); // "Line 1 Line 2 Line 3"
?>