|
| HOW TO USE THE trim() FUNCTION IN PHP
The trim() function strips specified characters from beginning and end of a string. It takes two parameters: the string to perform the action on and the specified character/s to strip out from the beginning and end of that string.
If the characters to strip are not specified, then trim() strips all whitespace (" "), new line "\n", tab ("\t"), carriage return ("\r") by default.
Example:
$string=" John James was here ";
$newstring=trim($string);
echo $newstring;
The above will output: John James was here
This is a good function to use when, for example, a user enters something in the input field of a site form but mistakenly leaves a whitespace before the actual entry. Technically, whitespace John is not the same as John as whitespace is considered a character as well.
You can also specify what character/s to strip from the beginning and end of a string.
Example:
$string="eggs sold here";
$newstring=trim($string,"e");
echo $newstring;
The above will output: ggs sold her
The e at the beginning of the string and the e at the end of the string are stripped out.
Say you only want to strip the e at the right (ie. at the end of the string), then use:
$string="eggs sold here";
$newstring=rtrim($string,"e"); // right trim
echo $newstring;
The above will output: eggs sold her
Say you only want to strip the e at the left (ie. at the start of the string), then use:
$string="eggs sold here";
$newstring=ltrim($string,"e"); // left trim
echo $newstring;
The above will output: ggs sold here
|
|