Remove blank spaces from a string in PHP

This article, will discuss multiple ways to remove blank spaces from a string in PHP.

Table Of Contents

Background

Removing blank spaces from a string is a common task in PHP, especially when dealing with user input, generating URLs, or processing text data. The goal is to eliminate all spaces from the string, including those at the beginning, end, and middle.

For example, if you have the following string:

$originalString = " This is a sample string ";

Your aim is to transform it into:

"Thisisasamplestring"

Let’s look at some methods to accomplish this.

Solution 1: Using str_replace()

The str_replace() function is used to replace all occurrences of a search string in a string with a replacement string. In this case, we can use it to replace spaces with nothing.

Let’s see the complete example,

<?php
$originalString = " This is a sample string ";

// Replace all spaces with an empty string
$noSpaceString = str_replace(' ', '', $originalString);

echo $noSpaceString; // Outputs: "Thisisasamplestring"
?>

Output

Thisisasamplestring

In this code:
– We are replacing every space (‘ ‘) in $originalString with an empty string (”).
– str_replace() will remove all occurrences of spaces, resulting in a string without any spaces.

Solution 2: Using preg_replace()

If you also want to remove other whitespace characters like tabs or new lines, preg_replace() with a regular expression is a better choice. This function performs a regular expression search and replace.

Let’s see the complete example,

<?php
$originalString = " This is a sample string ";

// Define a pattern to match all whitespace characters
$pattern = '/s+/';

// Replace all whitespace characters with an empty string
$noSpaceString = preg_replace($pattern, '', $originalString);

echo $noSpaceString; // Outputs: "Thisisasamplestring"
?>

Output

Thisisasamplestring

In this code:
– $pattern is a regular expression that matches any whitespace character (spaces, tabs, newlines).
– preg_replace($pattern, ”, $originalString) replaces all occurrences of whitespace characters with an empty string.
– This method ensures that all types of blank spaces are removed from the string.

Summary

To remove blank spaces from a string in PHP, str_replace() is a straightforward method for eliminating only spaces, while preg_replace() with an appropriate regular expression is more comprehensive, removing all kinds of whitespace characters. The choice between them depends on whether you need to remove just spaces or all whitespace characters.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top