Code Logo

Remove Spaces

Published at24 Jul 2026
PHP String Handling Easy 0 views
Like0

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

Example 1
Input
" "
Output
""
Example 2
Input
"Hello World"
Output
"HelloWorld"
Example 3
Input
""
Output
""
Example 4
Input
" spaces "
Output
"spaces"
Example 5
Input
"a b c"
Output
"abc"

Algorithm Flow

Recommendation Algorithm Flow for Remove Spaces
Recommendation Algorithm Flow for Remove Spaces

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 - Approach 1
<?php
function removeSpaces($text) {
    return str_replace([' ', "\t", "\n", "\r"], '', $text);
}