The trim Function
The trim
function removes whitespace from the beginning
and end of a string. It can also remove other
characters if specified as the second parameter.
Syntax
trim(string $string, string $characters = " \t\n\r\0\x0B"): string
Example
Let's remove whitespace from the edges of the string:
<?php
echo(trim(' abcde '));
?>
Code execution result:
'abcde'
Example
Let's remove slashes from the edges of the string:
<?php
echo trim('/abcde/', '/');
?>
Code execution result:
'abcde'
Example
Let's remove slashes and dots from the edges of the string:
<?php
echo trim('/abcde.', '/.');
?>
Code execution result:
'abcde'
Example
The function removes any number of specified characters if they are on the edge:
<?php
echo trim('../../abcde...', '/.');
?>
Code execution result:
'abcde'
Example
A range of characters can be specified using
two dots '..'
. For example, let's specify
that we want to remove characters from 'a'
to 'd'
:
<?php
echo trim('abcde', 'a..d');
?>
Code execution result:
'e'