Backend Development 3 min read

Using PHP trim() to Remove Whitespace and Specified Characters

This article explains PHP's trim() function, its parameters and default character list, and provides multiple code examples showing how to trim strings, binary data, and array elements, including custom functions and array_walk usage, with the resulting outputs displayed.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP trim() to Remove Whitespace and Specified Characters

trim() removes whitespace or specified characters from the beginning and end of a string in PHP. It accepts the string to process ( $str ) and an optional $charlist defining characters to strip, which can include ranges using "..". By default it removes space (ASCII 32), tab (\t), newline (\n), carriage return (\r), null byte (\0), and vertical tab (\x0B).

Example 1 demonstrates trimming a string containing tabs and newlines, cleaning binary data, and trimming a simple string:

<?php
$text = "\t\tThese are a few words :) ...  ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = trim($text);
var_dump($trimmed);
$trimmed = trim($text, " \t.");
var_dump($trimmed);
$clean = trim($binary, "\x00..\x1F");
var_dump($clean);
?>

The output shows the original strings and the results after applying trim() with default and custom character lists.

Example 2 defines a helper function trim_value that trims a variable by reference, then applies it to each element of an array using array_walk :

<?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 resulting array displays all fruit strings without leading or trailing whitespace.

BackendPHPdata cleaningTRIMstring-manipulationphp-functions
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.