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:

<?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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendStringfunction.trimWhitespace
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

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.