This article, will discuss multiple ways to remove spaces from a string in PHP.
Table Of Contents
Introduction
In PHP, strings may contain unwanted spaces, either between words or at the beginning and end of the string. You might need to remove these spaces for reasons such as data validation, formatting, or preparing data for storage or further processing. The goal is to remove all spaces from a string efficiently.
For example, if we have string like this,
$originalString = "This is a sample string";
Then after removing all spaces from this string the modified string will be like,
Thisisasamplestring
Let’s see how to do this.
Method 1: Using str_replace
The str_replace function in PHP replaces all occurrences of a search string with a replacement string in a given string. To remove spaces, we can use str_replace to replace all space characters with an empty string. The syntax of str_replace is:
Frequently Asked:
- Remove spaces from a String in PHP
- Remove characters from String after a character in PHP
- Remove the Last character from a String in PHP
- Remove a string after a comma in PHP
str_replace(mixed $search, mixed $replace, mixed $subject [, int &$count ])
Here, $search is the value to search for, $replace is the replacement value, and $subject is the string to search and replace in.
Let’s see the complete example,
<?php $originalString = "This is a sample string"; // Remove all spaces $modStr = str_replace(" ", "", $originalString); echo $modStr; ?>
Output
Thisisasamplestring
In this code, $originalString is the string from which we want to remove spaces. We use str_replace to create $modStr, which is the original string with all spaces removed.
Method 2: Using preg_replace
Another way to remove spaces from a string in PHP is by using the preg_replace() function. This function performs a regular expression search and replace. We can use a regular expression to match all space characters and replace them with an empty string.
Let’s see the complete example,
<?php $originalString = "This is a sample string"; // Remove all spaces using regular expression $noSpaceString = preg_replace('/s+/', '', $originalString); echo $noSpaceString; // Outputs: Thisisasamplestring ?>
Output
Thisisasamplestring
Here, /s+/ is the regular expression pattern that matches all whitespace characters (including spaces, tabs, and newlines). preg_replace replaces these matched characters with an empty string, effectively removing them from $originalString.
Summary
In PHP, removing spaces from a string can be done efficiently using either the str_replace function or the preg_replace function. The str_replace method is more straightforward for this specific task, while preg_replace offers more flexibility and power, especially when dealing with different types of whitespace characters.