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.

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.

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

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.