Remove Spaces
Remove all whitespace characters from a string using PHP.
Write a PHP function that removes all whitespace from a string. Use str_replace() with an array of whitespace characters [' ', "\t", "\n", "\r", "\f"] and replace with empty string.
The str_replace() function accepts an array of search values, making it efficient for multiple replacements. This approach handles spaces, tabs, newlines, carriage returns, and form feeds.
An alternative uses preg_replace('/\s+/', '', \$text) which matches all Unicode whitespace characters with the regex \s+.
Edge cases include empty strings (return ''), strings with only whitespace (return ''), and strings with mixed whitespace types.
Time complexity is O(n). Space complexity is O(n).
Whitespace removal is a common text preprocessing step in data cleaning. The str_replace() function with an array parameter efficiently removes multiple character types in a single pass. Alternative methods include preg_replace() for regex-based whitespace matching.
Understanding how to manipulate strings by removing unwanted characters is fundamental to text processing. The function handles common whitespace types: spaces, tabs, newlines, and carriage returns.
Example Input & Output
Algorithm Flow

Solution Approach
Write a PHP function that removes all whitespace from a string. Use str_replace() with an array of whitespace characters [' ', "\t", "\n", "\r", "\f"] and replace with empty string.
The str_replace() function accepts an array of search values, making it efficient for multiple replacements. This approach handles spaces, tabs, newlines, carriage returns, and form feeds.
An alternative uses preg_replace('/\s+/', '', \$text) which matches all Unicode whitespace characters with the regex \s+.
Edge cases include empty strings (return ''), strings with only whitespace (return ''), and strings with mixed whitespace types.
Time complexity is O(n). Space complexity is O(n).
Best Answers
<?php
function removeSpaces($text) {
return str_replace([' ', "\t", "\n", "\r"], '', $text);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
