To strip all spaces out of a string in PHP, the code is as follows−
Example
<?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
<?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
<?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