Backend Development 3 min read

Using PHP trim() to Remove Whitespace and Specified Characters

This article explains PHP's trim function, its syntax, optional character list parameter, and provides code examples showing how to remove surrounding spaces and custom characters, while also mentioning related ltrim and rtrim functions for one‑sided trimming.

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

In PHP programming, handling strings often requires removing whitespace from both ends, and the built‑in trim function provides this capability.

The syntax of trim is string trim ( string $str [, string $charlist ] ) , where $str is the input string and $charlist (optional) specifies characters to strip.

Example 1 demonstrates trimming spaces:

// Example string
$str = "   Hello, World!   ";

// Remove spaces from both ends
$result = trim($str);

// Output result
echo $result;

The code outputs Hello, World! .

Example 2 shows removing specific characters (asterisks) by passing a second argument:

// Example string
$str = "**Hello, World!**";

// Remove '*' characters from both ends
$result = trim($str, "*");

// Output result
echo $result;

The result is Hello, World! without the asterisks.

Besides trim , PHP also offers ltrim and rtrim to trim only the left or right side of a string, respectively.

Summary

trim removes whitespace and optional characters from both ends of a string.

Its syntax is string trim ( string $str [, string $charlist ] ) .

Providing a second argument allows removal of specific characters.

ltrim and rtrim perform one‑sided trimming.

Understanding trim helps developers handle strings efficiently in PHP applications.

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.