How to Remove White Space from a String in PHP

09/04/2021

Contents

In this article, you will learn how to remove white space from a string in PHP.

PHP trim() Function

In PHP, you can use the trim() function to remove whitespace from the beginning and end of a string. This function removes whitespace (or other specified characters) from the beginning and end of a string. By default, it removes spaces, tabs, and newlines, but you can specify additional characters to remove by providing them as a second argument to the function. For example, trim($string, " \t\n\r\0\x0B.") will remove spaces, tabs, newlines, null bytes, and dots from the beginning and end of the string.

Here is an example:

<?php
  $string = "  Hello, World!  ";
  $string = trim($string);
  // $string is now "Hello, World!"
?>

PHP ltrim() and rtrim() Functions

You can also use the ltrim() and rtrim() functions to remove whitespace from the left or right side of a string, respectively. These functions work similarly to trim(), but only remove whitespace (or other specified characters) from the left side or right side of a string, respectively. For example, ltrim($string, " \t\n\r\0\x0B.") will remove spaces, tabs, newlines, null bytes, and dots from the beginning of the string.

Here is an example:

<?php
  $string = "  Hello, World!  ";
  $string = ltrim($string);
  // $string is now "Hello, World!  "
  $string = rtrim($string);
  // $string is now "  Hello, World!"
?>

PHP preg_replace() Function

If you want to remove all whitespace from a string, you can use the preg_replace() function with a regular expression that matches any whitespace character.

This function uses regular expressions to search for and replace patterns in a string. The first argument is a regular expression pattern, and the second argument is the replacement string. In this case, we used the pattern /\s+/ which matches one or more whitespace characters (spaces, tabs, newlines, etc.). The + means “one or more” of the preceding character, in this case \s which means any whitespace. The third argument is the input string.

Here is an example:

<?php
  $string = "  Hello,\n  World!  ";
  $string = preg_replace('/\s+/', '', $string);
  // $string is now "Hello,World!"
?>

Note that preg_replace() will remove all spaces, newlines, tabs, etc. from the string, not just spaces.

PHP str_replace() Function

You can also use str_replace() function to remove spaces in a string. The first argument is the value you want to replace, the second argument is the value you want to replace with and the third argument is the input string.

Here is an example:

<?php
  $string = "Hello World";
  $string = str_replace(" ", "", $string);
  //$string is now "HelloWorld"
?>

There are multiple ways to remove whitespaces from a string in PHP and the best one to use depends on the specific requirements of your application.