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
\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!  
";
$result = trim($str);
echo $result; // outputs: Hello, World!

Removing whitespace, newline, and tab characters:

$str = "    Hello, World!
";
$result = trim($str, "
    ");
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.

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.

PHPfunctions.trimString 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

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.