Remove white spaces from a string in PHP

In this tutorial, we will see how we can remove white spaces from a string in PHP. We will see various functions to do the same.

Remove White Spaces in PHP

Removing white spaces from strings in PHP. We will see various methods and each method work differently. Here in this tutorial, we will see how we can remove whitespaces using two built-in functions such as str_replace() and preg_replace() in PHP. White Spaces are blank space which is created using either pressing the space button or the tab button.

To replace all the white spaces from a given string we can make use of the str_replace() method.

Syntax:

str_replace(Search Value, Replace Value, Subject Value, count)

Suppose we have an example, removing white spaces from “My name is John” will be “MynameisJohn“. We can see this through the following code.

<?php
// Declare a string
$myStr = "  Code    Speedy   Tutorial  ";      
$str = str_replace(' ', '', $myStr);
echo $str; 
?>
OUTPUT:
CodeSpeedyTutorial

Next, we will see about theĀ  preg_replace() method. It is used for replacing the content from the string after searching that content in the string.

Syntax:

preg_replace(Pattern, replacement, subject, limits, count )

Let’s understand with code.

<?php 
// Declare a string 
$myStr = " Hello Learners Code Speedy Tutorial "; 
$str = preg_replace('/\s+/', '', $myStr); 
echo $str; 
?>
OUTPUT:
HelloLearnersCodeSpeedyTutorial

Hope you liked this tutorial. Please do share with your friends.

Also Read: Reverse words in a given string in PHP

Comments are closed.