PHP trim() function is “used to remove whitespace or any specific characters from both the left and right sides of a string.”
Syntax
trim($string, $charlist)
Parameters
$string(required): The string to be trimmed.
$charlist(optional): It specifies the characters to be removed from the string. If not specified, it will default to trimming the following characters:
- “\0” – NULL
- “\t” – tab
- “\n” – a new line
- “\x0B” – vertical tab
- “\r” – carriage return
- ” ” – ordinary white space
Return value
It returns a modified string with whitespace or the specified characters removed from both sides.
Visual Representation
Example 1: How to Use trim() function
<?php
$str = " Hello AppDividend ";
echo "Without trim: " . $str;
echo "\n";
echo "With trim: " . trim($str);
Output
Without trim: Hello AppDividend
With trim: Hello AppDividend
Example 2: Passing a second parameter
<?php
$str = "Hello AppDividend";
echo "Without trim: " . $str;
echo "\n";
echo "With trim: " . trim($str,"Dividend");
Output
Without trim: Hello AppDividend
With trim: Hello App
Example 3: How to trim array values
To trim an array, combine the trim() and array_walk() functions.
<?php
function trim_array_value(&$value)
{
$value = trim($value);
}
$str = array('Mike', 'Robin', ' Eleven ');
echo "Without trim: \n" ;
var_dump($str);
array_walk($str, 'trim_array_value');
echo "With trim: \n" ;
var_dump($str);
Output
Without trim:
array(3) {
[0]=>
string(4) "Mike"
[1]=>
string(5) "Robin"
[2]=>
string(8) " Eleven "
}
With trim:
array(3) {
[0]=>
string(4) "Mike"
[1]=>
string(5) "Robin"
[2]=>
string(6) "Eleven"
}
In the output, you can see that the spaces before and after ‘Eleven’ have been removed after the array_walk with trim_array_value function is applied.
The ltrim() and rtrim() functions remove whitespaces or other characters from the left and right sides of the string.