We can remove blank space from left side of any string by using ltrim function.
$text= " This is my text";
echo $text;
$text=ltrim($text);
echo $text;
Same way we can remove blank space from right side of any string by using rtrim function.
$text= "This is my text ";
echo $text;
$text=rtrim($text);
echo $text;
To remove extra blank space, line break, carriage return from both sides ( left and right ) of a string we can use trim function
$text= " This string has blank space at both sides ";
echo $text;
$text=trim($text);
echo $text;
We can remove chars from the end of the string like this.
$str=' Hello +';
echo rtrim($str,'+');
We removed the extra '+' at the end of the string, similarly we can remove extra , or any other chars from the end of the string.
$str=' Hello Welcome';
echo rtrim($str,'come');
Output is hereHello Wel
Remove blank space present inside a string
We may not like to have blank space present within a string (example: userid entered by user in signup page ) . We can search and inform the user about this or remove the blank space from the string variable.
Searching for presence of white space.
We will use strstr() to check for presence of white space
$string='ABCD XYZ';
if (strstr($string,' ')) {
echo " Blank space is present ";
}else{
echo " Blank space is NOT present ";
}
Remove blank space
We will use str_replace() to remove blank space from a string.
$new_string=str_replace(' ','',$string);
echo $new_string;