Backend Development 4 min read

How to Use PHP trim() Function to Remove Whitespace and Specified Characters

This article explains the PHP trim() function, detailing its syntax, parameters, and usage for removing leading and trailing whitespace or custom characters, and provides multiple code examples illustrating basic trimming, character masking, and common scenarios in string processing.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP trim() Function to Remove Whitespace and Specified Characters

The trim() function is a widely used PHP built‑in that removes whitespace or other specified characters from the beginning and end of a string.

1. Function Syntax

The syntax of trim() is:

trim(string $str, string $character_mask = " \t\n\r\0\x0B") : string

The first argument is the target string, and the optional second argument defines a mask of characters to strip; by default it removes spaces, tabs, newlines, carriage returns, null bytes, and vertical tabs.

2. Removing Leading and Trailing Spaces

To strip only whitespace, pass the string to trim() :

$str = "  hello world  ";
$result = trim($str);
echo $result; // outputs: hello world

3. Removing Specified Characters

You can also specify characters to remove via the second parameter $character_mask :

$str = "Hello, World!";
$result = trim($str, "H!");
echo $result; // outputs: ello, World

4. Common Examples

Removing whitespace and newline characters:

$str = "  Hello, World!  \n";
$result = trim($str);
echo $result; // outputs: Hello, World!

Removing whitespace, newline, and tab characters:

$str = "    Hello, World!\n";
$result = trim($str, "\n    ");
echo $result; // outputs: Hello, World!

5. Summary

The trim() function is essential for cleaning user input and ensuring data accuracy in PHP applications, offering flexible removal of both default whitespace and any custom characters you define.

functionsTRIMstring-manipulation
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

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.