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:
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "
";
$trimmed = trim($text);
var_dump($trimmed);
$trimmed = trim($text, " \t.");
var_dump($trimmed);
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
?>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.
<?php
function trim_value(&$value) {
$value = trim($value);
}
$fruit = array('apple', 'banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>The final array contains the fruit names without surrounding whitespace.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
