How to strip all spaces out of a string in PHP?


To strip all spaces out of a string in PHP, the code is as follows−

Example

 Live Demo

<?php
   $str = "this is a test string";
   strtr($str,[' '=>'']);
   echo $str
?>

Output

This will produce the following output−

Thisisateststrin

To remove the whitespaces only, the below code can be used−

Example

 Live Demo

<?php
   $str = "this is a test string";
   $str = str_replace(' ', '', $str);
   echo $str
?>

Output

This will produce the following output. The str_replace function replaces the given input string with a specific character or string−

thisisateststring

To remove whitespace that includes tabs and line end, the code can be used−

Example

 Live Demo

<?php
   $str = "this is a test string";
   $str = preg_replace('/\s/', '', $str);
   echo $str
?>

Here, the preg_match function is used with regular expressions. It searches for a pattern in a string and returns True if the pattern exists and false otherwise. This will produce the following output−

thisisateststring

Updated on: 27-Dec-2019

266 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements