trim

trim($string)

The trim function strips so-called whitespace from the start and the end of a string. Whitespace means spaces, tabs, line breaks and a few other characters.

By default trim removes these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.

echo "T"." OD "."O"; // T OD O
echo "T".trim(" OD ")."O"; // TODO

The trim function can also have a second parameter, the list of characters to remove from the start and the end of the string – trim($string, $characters). With the second parameter the function works only with the characters given in it and no longer removes the default whitespace. The list can also contain ranges of characters, for example trim($string, "\x00..\x1F").

echo trim("TODO", "TO"); // D
echo "T".trim(" OD ", " D")."O"; // TOO
$string = "\x01\x02Hello\x1F";
echo trim($string, "\x00..\x1F"); // Hello

Related functions:
ltrim()
rtrim()