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.
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.
This program uses the trim, ltrim and rtrim functions. We see all 3 functions in the trim family—each has a similar result.
trim()
with no arguments on the string
containing the word "Bird" and it removes both the start and end whitespace.ltrim()
we only remove the whitespace at the start. It handles both newlines and spaces (and any number of them).Rtrim()
handles whitespace at the end (the right side) of the string
. We see the result has no end newline or space.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 "
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.