How to Remove All White Spaces from a String in PHP

Here are 3 ways to remove all whitespace from a String in PHP,

  1. Using “str_replace()” function
  2. Using “str_ireplace()” function
  3. Using “preg_replace()” function

Method 1: Using the str_replace() MethodVisual Representation of Remove All White Spaces from a String in PHP(str_replace() Method)

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

Syntax

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

Example

<?php

$str = " Homer Simpson is the best ";

$str = str_replace(' ', '', $str);

echo $str, "\n";

Output

HomerSimpsonisthebest

Method 2: Using the str_ireplace() MethodVisual Representation of Remove All White Spaces from a String in PHP(str_ireplace() Method)

The str_ireplace() function is used to replace all the occurrences of the search string (” “) with the replacing string (“”) in the given string. It is a case-insensitive version of the str_replace() function.

Syntax

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

Example

<?php

$str = " Homer Simpson is the best ";

$str = str_ireplace(' ', '', $str);

echo $str, "\n";

Output

HomerSimpsonisthebest

Method 3: Using the preg_replace() MethodVisual Representation of Remove All White Spaces from a String in PHP(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

$str = " Homer Simpson is the best ";

$str = preg_replace('/\s+/', '', $str);

echo $str, "\n";

Output

HomerSimpsonisthebest

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.