Backend Development 3 min read

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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP trim() Function: Removing Whitespace and Specified Characters

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.

backendphpString()functionTRIMwhitespace
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.