Question
How can I remove all spaces from a string in PHP?
For example:
$string = "this is my string";
I want the output to be:
"thisismystring"
What is the correct way to do this in PHP?
Short Answer
By the end of this page, you will understand how to remove spaces from strings in PHP, when to use str_replace() versus regular expressions, and how to avoid common mistakes when working with whitespace.
Concept
In PHP, removing spaces from a string usually means creating a new version of the string without certain characters.
The most common tool for this is str_replace(), which replaces one substring with another. If you replace a space (" ") with an empty string (""), all normal space characters are removed.
$string = "this is my string";
$result = str_replace(" ", "", $string);
echo $result; // thisismystring
This matters because string cleaning is very common in programming. Developers often remove spaces when:
- normalizing user input
- generating usernames or slugs
- cleaning imported data
- comparing text values
- formatting IDs, phone numbers, or codes
A key detail is that a space is not always the same as whitespace.
- A normal space is
" " - Other whitespace characters include:
- tabs (
\t) - newlines (
\n) - carriage returns (
\r)
- tabs (
So if your goal is only to remove visible space characters, str_replace(" ", "", $string) is enough. If you want to remove all whitespace characters, a regular expression is usually better.
Mental Model
Think of a string like a row of tiles:
t h i s _ i s _ m y _ s t r i n g
Each _ represents a space. Removing spaces means scanning through the row and taking out every tile that matches a space.
str_replace()says: "Whenever you see this exact tile, remove it."preg_replace()says: "Whenever you see any tile matching this pattern, remove it."
So:
- use
str_replace()for exact characters - use
preg_replace()for flexible pattern matching
Syntax and Examples
The most common syntax is:
str_replace(search, replace, subject)
To remove all normal spaces:
$string = "this is my string";
$result = str_replace(" ", "", $string);
echo $result;
Output:
thisismystring
Example: remove spaces from user input
$username = "john doe";
$cleanUsername = str_replace(" ", "", $username);
echo $cleanUsername; // johndoe
Example: remove all whitespace, not just spaces
$text = "this\tis\nmy string";
$result = preg_replace('/\s+/', , );
;
Step by Step Execution
Consider this code:
$string = "this is my string";
$result = str_replace(" ", "", $string);
echo $result;
Here is what happens step by step:
-
$stringis assigned the value:"this is my string" -
str_replace(" ", "", $string)is called.- Search for:
" " - Replace with:
"" - In this string:
"this is my string"
- Search for:
-
PHP looks through the string and finds every normal space character.
-
Each space is replaced with an empty string, which means it is removed.
-
The new value becomes:
"thisismystring" -
That result is stored in
$result.
Real World Use Cases
Removing spaces from strings is useful in many practical situations.
1. Cleaning form input
Users may enter values with spaces you do not want.
$postalCode = "12 345";
$cleanPostalCode = str_replace(" ", "", $postalCode);
2. Formatting phone numbers or IDs
$phone = "123 456 7890";
$cleanPhone = str_replace(" ", "", $phone);
3. Creating usernames
$name = "Jane Doe";
$username = strtolower(str_replace(" ", "", $name));
// janedoe
4. Data import and cleanup
CSV or copied data often contains inconsistent spacing.
$productCode = ;
= (, , );
Real Codebase Usage
In real PHP projects, developers usually combine string cleanup with validation and normalization.
Common pattern: normalize before saving
$emailInput = " john doe@example.com ";
$normalized = trim($emailInput);
If spaces inside the value are not allowed:
$normalized = str_replace(" ", "", trim($emailInput));
Common pattern: guard clause for empty input
function normalizeCode(string $code): string
{
$code = trim($code);
if ($code === '') {
return '';
}
return str_replace(' ', '', $code);
}
This avoids extra processing on empty values.
Common Mistakes
Here are common mistakes beginners make when removing spaces in PHP.
1. Using trim() when you want to remove all spaces
trim() only removes whitespace at the beginning and end.
Broken expectation:
$string = "this is my string";
echo trim($string); // still contains inner spaces
Use this instead:
echo str_replace(" ", "", $string);
2. Forgetting that strings are immutable in practice
str_replace() returns a new string. It does not permanently modify the variable unless you assign the result.
Broken code:
$string = "a b c";
str_replace(" ", "", $string);
echo $string; // a b c
Correct:
Comparisons
| Task | Best PHP Function | What it does |
|---|---|---|
| Remove all normal spaces | str_replace(" ", "", $string) | Removes every regular space character |
| Remove whitespace at start/end only | trim($string) | Keeps inner spaces unchanged |
| Remove tabs, newlines, and spaces | preg_replace('/\\s+/', '', $string) | Removes all whitespace characters |
| Replace repeated spaces with one space | preg_replace('/ +/', ' ', $string) | Collapses multiple spaces into one |
str_replace() vs preg_replace()
| Function | Use when |
|---|
Cheat Sheet
// Remove all normal spaces
$result = str_replace(' ', '', $string);
// Remove spaces from the same variable
$string = str_replace(' ', '', $string);
// Remove whitespace at the start and end only
$result = trim($string);
// Remove all whitespace: spaces, tabs, newlines
$result = preg_replace('/\s+/', '', $string);
Quick rules
- Use
str_replace()for exact character replacement. - Use
trim()for outer whitespace only. - Use
preg_replace('/\s+/', '', ...)for all whitespace. - Reassign the result if you want to update the variable.
Common examples
str_replace(' ', '', 'a b c'); // abc
();
(, , );
FAQ
How do I remove all spaces from a string in PHP?
Use:
$result = str_replace(' ', '', $string);
This removes all normal space characters.
How do I remove all whitespace, not just spaces?
Use a regular expression:
$result = preg_replace('/\s+/', '', $string);
This removes spaces, tabs, and newlines.
Does trim() remove all spaces in PHP?
No. trim() only removes whitespace from the beginning and end of a string.
Does str_replace() modify the original string?
No. It returns a new string. Assign the result back to a variable if needed.
Which is better: str_replace() or preg_replace()?
If you only need to remove normal spaces, str_replace() is better because it is simpler and clearer.
Can I remove only leading and trailing spaces?
Mini Project
Description
Build a small PHP utility that normalizes product codes entered by users. Product codes may contain spaces, tabs, or accidental line breaks, and you want to store a clean version for comparison and lookup.
Goal
Create a PHP script that removes whitespace from product code input and outputs a normalized version.
Requirements
- Accept a string containing a product code.
- Remove all normal spaces from the code.
- Also create a version that removes all whitespace characters.
- Display both results clearly.
- Use valid PHP string functions.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.