Open In App
Related Articles

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

Improve Article
Improve
Save Article
Save
Like Article
Like

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:

Method 1: 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

Method 2: 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

Method 3: 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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 27 May, 2020
Like Article
Save Article
Similar Reads
Related Tutorials