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);
var_dump($result);
// Part 2: use ltrim to trim left side.
$result = ltrim($line);
var_dump($result);
// Part 3: use rtrim to trim right side.
$result = rtrim($line);
var_dump($result);
// Part 4: specify an argument to trim to remove certain characters only.
$result = trim($line, "\n");
var_dump($result);string(4) "Bird"
string(6) "Bird
"
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 26, 2023 (image).