Using PHP trim() Function to Remove Whitespace and Specified Characters

This article explains the PHP trim() function, its parameters, default behavior, and how to use it with optional character masks to remove whitespace or specific characters from the ends of strings, accompanied by clear code examples.

php Courses
php Courses
php Courses
Using PHP trim() Function to Remove Whitespace and Specified Characters

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

Basic usage of trim()

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

The function accepts two parameters: the target string $str and an optional character mask $character_mask. By default, the mask removes spaces, tabs, newlines, and other whitespace characters from the string ends.

Usage example

The following example demonstrates the basic use of trim():

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

The output shows that the leading and trailing spaces have been removed, leaving "Hello, World!".

Beyond the default behavior, trim() can also remove specific characters by providing a $character_mask argument.

For instance, the code below removes the characters "X" and "O" from both ends of the string:

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

The result confirms that only the leading and trailing "X" and "O" characters are stripped, while the interior content remains unchanged.

Note that trim() only affects characters at the start and end of a string; it does not modify characters inside the string.

Understanding and applying trim() can greatly improve efficiency when processing strings in everyday PHP development.

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.

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