Question

How to Remove Spaces from a String in PHP

phpstringspaces

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)

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.

$result = preg_replace('/\s+/', '', $string);

Use the simpler tool when possible. If you only need to remove normal spaces, str_replace() is clearer and easier to read.

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
Take Quiz

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+/', '', $text);

echo $result; // thisismystring

Example: remove spaces only at the beginning and end

If you only want to remove outer spaces, use trim() instead:

$text = "  hello world  ";
$result = trim($text);

echo $result; // hello world

When to choose which

  • str_replace(" ", "", $string) → remove normal spaces everywhere
  • preg_replace('/\s+/', '', $string) → remove all whitespace characters
  • trim($string) → remove whitespace only from the start and end

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:

  1. $string is assigned the value:

    "this is my string"
    
  2. str_replace(" ", "", $string) is called.

    • Search for: " "
    • Replace with: ""
    • In this string: "this is my string"
  3. PHP looks through the string and finds every normal space character.

  4. Each space is replaced with an empty string, which means it is removed.

  5. The new value becomes:

    "thisismystring"
    
  6. That result is stored in $result.

  7. echo $result; prints:

    thisismystring
    

Small trace example

Input:

"a b c"

Character by character:

  • a → keep
  • → remove
  • b → keep
  • → remove
  • c → keep

Final result:

"abc"

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 = "AB 123 CD";
$normalized = str_replace(" ", "", $productCode);

5. Comparing values consistently

$a = "order id";
$b = "orderid";

$match = str_replace(" ", "", $a) === str_replace(" ", "", $b);

This helps when spaces should not affect equality.

Take Quiz

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 pattern: remove multiple whitespace types

When data comes from pasted text or files, tabs and newlines may appear.

function removeAllWhitespace(string $value): string
{
    return preg_replace('/\s+/', '', $value);
}

Common pattern: chain normalization steps

$input = " Product 123 ";
$clean = strtoupper(str_replace(' ', '', trim($input)));
// PRODUCT123

In codebases, readability matters. If you only need to remove spaces, str_replace() is usually preferred because it clearly shows intent.

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:

$string = "a b c";
$string = str_replace(" ", "", $string);
echo $string; // abc

3. Removing only normal spaces when tabs or newlines are present

Broken code:

$text = "a\tb\nc";
echo str_replace(" ", "", $text); // tabs/newlines remain

Correct:

echo preg_replace('/\s+/', '', $text);

4. Confusing empty string with a space

A space is " ", not "".

Broken code:

str_replace("", "", $string);

Correct:

str_replace(" ", "", $string);

5. Not thinking about whether spaces should be removed at all

Sometimes spaces are meaningful. For example, removing spaces from a full name may not be appropriate for display.

Ask yourself:

  • Is this for display?
  • Is this for comparison?
  • Is this for storage or normalization?

Choose the operation based on the actual goal.

Comparisons

TaskBest PHP FunctionWhat it does
Remove all normal spacesstr_replace(" ", "", $string)Removes every regular space character
Remove whitespace at start/end onlytrim($string)Keeps inner spaces unchanged
Remove tabs, newlines, and spacespreg_replace('/\\s+/', '', $string)Removes all whitespace characters
Replace repeated spaces with one spacepreg_replace('/ +/', ' ', $string)Collapses multiple spaces into one

str_replace() vs preg_replace()

FunctionUse whenProsCons
str_replace()You know the exact text to replaceSimple, readable, fast for basic replacementsDoes not match patterns
preg_replace()You need pattern matchingPowerful and flexibleSlightly harder to read for beginners

trim() vs removing spaces everywhere

OperationInputOutput
trim(" hello world ")" hello world ""hello world"
str_replace(" ", "", "hello world")"hello world""helloworld"

The main difference is simple:

  • trim() cleans edges
  • str_replace() removes matching characters everywhere
  • preg_replace() removes anything matching a pattern
Take Quiz

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
trim('  a b c  ');                    // a b c
preg_replace('/\s+/', '', "a\tb\nc"); // abc

Edge cases

  • str_replace(' ', '', $string) does not remove tabs or newlines.
  • trim() does not remove spaces inside the string.
  • preg_replace() may return null on regex error, though this is uncommon with a simple pattern like /\s+/.

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?

Yes. Use:

trim($string)

What if my string contains multiple kinds of whitespace?

Use:

preg_replace('/\s+/', '', $string)

That handles spaces, tabs, and line breaks.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more