Backend Development 4 min read

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

This article explains the PHP trim() function, its parameters, default behavior, and demonstrates how to remove leading and trailing whitespace or custom characters from strings with clear code examples and output results.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use 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 usage of trim() is:

string trim(string $str, string $character_mask = " \t\n\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 common whitespace characters.

Example 1 shows the default behavior:

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

Output:

Original string: '  Hello, World!   '
Trimmed string: 'Hello, World!'

In this example, the extra spaces around $str are removed by trim($str) , leaving a clean string.

Beyond the default usage, trim() can also remove specific characters by providing a $character_mask . Example 2 demonstrates removing the characters "X" and "O" from both ends of a string:

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

Output:

Original string: 'XOXHello, World!OXOX'
Trimmed string: 'Hello, World!'

This shows that trim($str, "XO") successfully strips the leading and trailing "X" and "O" characters.

Note that trim() only removes characters from the start and end of the string; characters inside the string remain untouched.

Summary

Through this guide, you have learned the basic usage of the trim() function, which can easily remove whitespace or specified characters from the ends of a string, making string handling in PHP more efficient.

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