How to strip all spaces out of a string in PHP?

In PHP, there are several methods to remove all spaces from a string. Each approach offers different capabilities for handling various types of whitespace characters.

Using str_replace()

The simplest method to remove only space characters from a string −

<?php
    $str = "this is a test string";
    $str = str_replace(' ', '', $str);
    echo $str;
?>
thisisateststring

Using strtr()

Alternative approach using character translation −

<?php
    $str = "this is a test string";
    $result = strtr($str, [' ' => '']);
    echo $result;
?>
thisisateststring

Using preg_replace() for All Whitespace

To remove all types of whitespace including spaces, tabs, and newlines −

<?php
    $str = "this is a test string<br>\t";
    $str = preg_replace('/\s/', '', $str);
    echo $str;
?>
thisisateststring

Comparison

Method Removes Performance
str_replace() Only spaces Fastest
strtr() Only spaces Fast
preg_replace() All whitespace Slower

Conclusion

Use str_replace() for removing only space characters, and preg_replace() with the \s pattern when you need to remove all types of whitespace including tabs and newlines.

Updated on: 2026-03-15T08:26:05+05:30

441 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements