Open In App

How to remove all white spaces from a string in PHP ?

Last Updated : 11 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string element containing some spaces and the task is to remove all the spaces from the given string str in PHP. In order to do this task, we have the following methods in PHP:

Using str_replace() Method

The str_replace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str.

Syntax:

str_replace($searchVal, $replaceVal, $subjectVal, $count)

Example :

PHP
<?php
// PHP program to remove all white
// spaces from a string 

// Declare a string
$str = "  Geeks for   Geeks  "; 
  
// Using str_replace() function 
// to removes all whitespaces  
$str = str_replace(' ', '', $str);

// Printing the result
echo $str; 
?>

Output
GeeksforGeeks

Using str_ireplace() Method

The str_ireplace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str. The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.

Syntax:

str_ireplace($searchVal, $replaceVal, $subjectVal, $count)

Example :

PHP
<?php
// PHP program to remove all
// white spaces from a string 
  
$str = "  Geeks for   Geeks  "; 
  
// Using str_ireplace() function 
// to remove all whitespaces  
$str = str_ireplace (' ', '', $str);

// Printing the result
echo $str; 
?>

Output
GeeksforGeeks

Using preg_replace() Method

The preg_replace() method is used to perform a regular expression for search and replace the content.

Syntax:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Example :

PHP
<?php
// PHP program to remove all
// white spaces from a string 
  
$str = "  Geeks for   Geeks  "; 
  
// Using preg_replace() function 
// to remove all whitespaces  
$str = preg_replace('/\s+/', '', $str);

// Printing the result
echo $str; 
?>

Output
GeeksforGeeks

Using explode() and implode()

Using explode() and implode() to remove all white spaces in a string involves splitting the string into an array of words with explode(‘ ‘, $string), then rejoining the array elements into a single string without spaces using implode(”, $array).

Example:

PHP
<?php
$string = "Hello World";

// Split the string into an array using space as the delimiter
$array = explode(' ', $string);

// Join the array elements into a single string without spaces
$stringWithoutSpaces = implode('', $array);

echo $stringWithoutSpaces; // Output: HelloWorld
?>

Output
HelloWorld

Using implode() with explode() to remove all spaces

Using `explode()` to split the string into an array at spaces and `implode()` to join array elements removes all spaces effectively. This approach transforms the string into a contiguous sequence of characters, useful for processing data where whitespace is irrelevant.

Example : PHP code splits the string “Hello World” into an array at spaces using `explode()`, then removes spaces by joining array elements with `implode()`, outputting “HelloWorld”.

PHP
<?php
$string = "Hello   World";
$splitString = explode(' ', $string); // Split the string into an array at spaces
$removedSpaces = implode('', $splitString); // Join array elements without spaces
echo $removedSpaces; // Outputs: "HelloWorld"
?>

Output
HelloWorld

Using filter_var()

Using filter_var() in PHP, you can remove all white spaces from a string. This function can sanitize the string by stripping high and low ASCII characters, effectively removing unwanted spaces.

Example:

PHP
<?php
$string = "Hello World!";
$noSpaces = filter_var($string, 
                       FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | 
                       FILTER_FLAG_STRIP_HIGH);
echo $noSpaces . PHP_EOL; // Output: HelloWorld!
?>

Output
Hello World!

Using str_split() and array_filter() Method

The str_split() function splits the string into an array of single characters. The array_filter() function is then used to remove the spaces from this array. Finally, implode() is used to join the remaining characters back into a string without spaces.

Example:

PHP
<?php
// PHP program to remove all white
// spaces from a string 

// Declare a string
$str = "  Geeks for   Geeks  "; 
  
// Split the string into an array of single characters
$charArray = str_split($str);

// Use array_filter to remove all spaces
$filteredArray = array_filter($charArray, function($char) {
    return $char !== ' ';
});

// Join the filtered array back into a string
$resultStr = implode('', $filteredArray);

// Printing the result
echo $resultStr; 
?>

Output
GeeksforGeeks

Using loop

In this approach we iterate through each character of a string and checks if it’s not a white space (‘ ‘, “\t”, “\n”, “\r”, “\0”, “\x0B”), and concatenate non-white space characters to build a new string.

Example: In this example we removes whitespace characters from a string ($string) using a loop and conditionals.

PHP
<?php
$string = "  Geeks  For  Geeks  !  ";
$cleanString = '';

for ($i = 0; $i < strlen($string); $i++) {
    if ($string[$i] !== ' ' && $string[$i] !== "\t" && $string[$i] !== "\n" 
        && $string[$i] !== "\r" && $string[$i] !== "\0" && $string[$i] !== "\x0B") {
        $cleanString .= $string[$i];
    }
}

echo $cleanString;
?>

Output
GeeksForGeeks!


Next Article

Similar Reads