Backend Development 3 min read

Using PHP trim() to Remove Whitespace and Specified Characters

This article explains the PHP trim() function, detailing its syntax, default behavior of removing whitespace, optional character mask usage, and provides clear code examples demonstrating both standard trimming and custom character removal, helping developers efficiently handle string preprocessing in backend development.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP trim() to Remove Whitespace and Specified Characters

In PHP development, handling strings is common, and the trim() function is a frequently used tool for removing whitespace from both ends of a string.

The basic signature of the function is:

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

It accepts the target string $str and an optional character mask $character_mask . By default, the mask removes spaces, tabs, newlines, and other whitespace characters.

A simple example demonstrates the default usage:

$str = "  Hello, World!   ";
echo "Original string: '" . $str . "'";
echo "Trimmed string: '" . trim($str) . "'";

The output shows the original string with surrounding spaces and the trimmed result without them.

Beyond the default behavior, trim() can remove specific characters by providing a character mask. For instance:

$str = "XOXHello, World!OXOX";
echo "Original string: '" . $str . "'";
echo "Trimmed string: '" . trim($str, "XO") . "'";

This removes the leading and trailing "X" and "O" characters, leaving only the core content.

It is important to note that trim() only affects characters at the beginning and end of the string; characters inside the string remain unchanged.

Summary

By mastering the trim() function, developers can easily eliminate unwanted whitespace or specified characters from strings, improving efficiency in everyday PHP backend development.

backendPHPTRIMstring-manipulationphp-functions
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.