PHP trim() Function: Removing Whitespace and Specified Characters
This article explains PHP's trim() function, detailing how it removes leading and trailing whitespace or custom characters, describes its parameters and return value, and provides multiple code examples demonstrating default usage, custom character lists, and applying trim via array_walk.
trim() removes whitespace or specified characters from the beginning and end of a string.
When called without a second argument, it strips space, tab, newline, carriage return, null byte, and vertical tab.
Parameters: string $str – the input string; string $charlist (optional) – list of characters to strip, which can include ranges like "..".
Return value: the filtered string.
Example 1:
Output shows the original strings and the results after trimming.
Example 2 defines a helper function trim_value(&$value) that applies trim() to a variable, then uses array_walk to trim each element of an array of fruit strings.
The final array contains the fruit names without surrounding whitespace.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.