PHP trim() function is used for removing the white space or other characters from starting and end of a string. Its used for formatting data properly. In some cases unnecessary whitespaces may be there in the beginning or end of a string, we can use this function to remove those blank spaces.
trim() function has an optional parameter for specifying the character to remove.
Its Syntax will be :
trim(string to be trimmed , character to remove );
By default it will remove the following character from the beginning and end of a string
- ” ” : an ordinarywhite space.
- “t” : a tab.
- “n” : a new line.
- “r” : a carriage return.
- “” : the NUL-byte.
- “x0B” : a vertical tab.
See the sample PHP program using trim function without parameter
<?php
$data=" how to remove blank spaces ";
$data1=trim($data);
echo $data.":<br>";
echo $data1.":<br>";
?>
Now check the display result source code in browser , we can see
how to remove blank spaces :<br>how to remove blank spaces:<br>
Here we can see that $data contain whitespaces at the starting and end , and $data1 doesn’t contain those things ( our trim function has removed that )…
By default output in browser we wont feel any difference between these data because browsers will automatically trim the data for output . Thats why we need to check the source code in browser for the real values.
Now we can write another program using trim function with parameter
<?php
$data="how to remove blank spaces how";
$data1=trim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>
Its output will be :
how to remove blank spaces how:<br> to remove blank spaces :<br>
Here we have specified “how” as optional parameter with trim function and “how” is removed from the beginning and end of the string.
There is two more trim function available
ltrim() : Left trim only; Will remove only from the beginning of a string ( starting )
rtrim() : Right trim only will remove only from the end of a string
Rest everything is same as trim() function.
See the sample php program with ltrim() function
<?php
$data="how to remove blank spaces how";
$data1=ltrim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>
Its output will be :
how to remove blank spaces how:<br> to remove blank spaces how:<br>
Here we can see that “how” is removed from the beginning of string and “how” at end remains
Now look at the program with rtrim()
<?php
$data="how to remove blank spaces how";
$data1=rtrim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>
Its output will be L
how to remove blank spaces how:<br>how to remove blank spaces :<br>
Here we can see that “how” is removed from end only, the beginning “how” remains in the ouput string .
We can use any of these function for remove the un necessary whitespaces or characters from the end or beginning or from both as per our requirement.
And note trim() = rtrim() + ltrim() in action.