PHP Remove Whitespace From String Example

Apr 12, 2021 . Admin

PHP Remove Whitespace From String Example

Hi Guys,

In this blog,I will explain you how remove white space from string You can use the PHP trim() function to remove whitespace including non-breaking spaces newlines, and tabs from the beginning and end of the string. It will not remove whitespace occurs in the middle of the string. Let's take a visual examination of an example to understand how it rudimentally works:

Method : 1
Syntax:
trim(string,charlist);
Example
<?php

    $my_str = '    Welcome to MyWebtuts.com ';
    echo strlen($my_str); // Outputs: 29
    echo $my_str."
"; $trimmed_str = trim($my_str); echo strlen($trimmed_str); // Outputs: 24 echo $trimmed_str."
"; ?>
Output
29    Welcome to MyWebtuts.com 
24Welcome to MyWebtuts.com
Method : 2

Now,Let's see another function to remove white space from string Utilizing str_replace() Method: The str_replace() method is utilized to supersede all the occurrences of the search string (” “) by replacing string (“”) in the given string str.

Syntax:
str_replace(find,replace,string,count)
Example
<?php

    // PHP program to remove all whitespaces from a string 
      
    // Declare a string
    $str = "  Welcome to   MyWebtuts.com  "; 
        
    // Using str_replace() function 
    // to removes all whitespaces  
    $str = str_replace(' ', '', $str);
      
    // Printing the result
    echo $str;

?>
Output
WelcometoMyWebtuts.com

The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.

Syntax:
str_ireplace(find,replace,string,count)
Example
<?php

    // PHP program to remove all whitespaces from a string 
      
    // Declare a string
    $str = "  Welcome to   MyWebtuts.com  "; 
        
    // Using str_ireplace() function 
    // to removes all whitespaces  
    $str = str_ireplace(' ', '', $str);
      
    // Printing the result
    echo $str;

?>
Output
WelcometoMyWebtuts.com
Method : 3

Using preg_replace() Method: The preg_replace() method is utilized to perform a regular expression for search and replace the content.

Syntax:
preg_replace(patterns, replacements, input, limit, count)
Example
<?php

    // PHP program to remove all whitespaces from a string 
      
    $str = "  Welcome to   MyWebtuts.com  "; 
        
    // Using preg_replace() function 
    // to remove all whitespaces  
    $str = preg_replace('/\s+/', '', $str);
      
    // Printing the result
    echo $str; 

?>
Output
WelcometoMyWebtuts.com
It will help you..
#PHP