Trim. Suppose we read a line from a text file in a PHP program. We usually need to remove the ending whitespace. We can use functions like trim for this purpose.
Related functions. With trim we remove whitespace from both the start and the end. With ltrim() we remove from the start. And rtrim and chop remove from the end.
Example. This program uses the trim, ltrim and rtrim functions. We see all 3 functions in the trim family—each has a similar result.
Part 1 We invoke trim() with no arguments on the string containing the word "Bird" and it removes both the start and end whitespace.
Part 2 With ltrim() we only remove the whitespace at the start. It handles both newlines and spaces (and any number of them).
Part 3 Rtrim() handles whitespace at the end (the right side) of the string. We see the result has no end newline or space.
Part 4 Trim and related functions can be used with a second argument. This tells us which characters (in a set) will be removed.
$line = " Bird \n";
// Part 1: use trim with no argument.
$result = trim($line);
// Part 2: use ltrim to trim left side.
$result = ltrim($line);
// Part 3: use rtrim to trim right side.
$result = rtrim($line);
// Part 4: specify an argument to trim to remove certain characters only.
$result = trim($line, "\n");
string(5) " Bird"
string(6) " Bird "
Chop. This function is known in scripting languages, so PHP provides an alias that maps chop() to rtrim(). It removes ending newlines and whitespace.
$line = " ??? ";
// Use chop to trim the right side only (the same as rtrim).
$chopped = chop($line);
var_dump($chopped);string(4) " ???"
Often PHP programs have similar requirements—they must process lines from a file, or clean up user input. With trim() and its siblings we perform common string manipulations.