Using PHP trim() Function to Remove Whitespace and Specified Characters
This article explains PHP's trim() function, its syntax and parameters, and provides clear code examples showing how to remove surrounding whitespace or custom characters from strings, while also mentioning related ltrim() and rtrim() functions for one‑sided trimming.
In PHP programming we often need to process strings, and a common requirement is to remove whitespace from both ends. PHP provides a built‑in trim function that is very useful for this purpose. This article introduces the usage of the trim function and provides code examples to help readers understand how to use it.
The trim function removes whitespace and other characters from the beginning and end of a string. Its syntax is:
<code>string trim ( string $str [, string $charlist ] )</code>Parameters:
$str : the string to be processed; it can be a variable or a literal string.
$charlist (optional): a list of characters to remove from both ends. If omitted, whitespace is removed by default.
To demonstrate basic usage, consider the following example:
<code>// Example string
$str = " Hello, World! ";
// Remove whitespace from both ends
$result = trim($str);
// Output the result
echo $result;</code>Running this code outputs the string "Hello, World!" without the surrounding spaces.
Beyond removing spaces, trim can also remove other specified characters. The next example shows how to strip asterisks (*) from both ends of a string:
<code>// Example string
$str = "**Hello, World!**";
// Remove asterisk characters from both ends
$result = trim($str, "*");
// Output the result
echo $result;</code>This produces the string "Hello, World!" with the leading and trailing asterisks removed.
In addition to trim , PHP offers ltrim and rtrim functions to remove characters from the left or right side of a string respectively; their usage is identical to trim but they affect only one end.
Summary
The trim function removes whitespace and optionally other characters from both ends of a string.
Syntax: string trim ( string $str [, string $charlist ] ) .
By providing a second argument, you can specify which characters to strip.
PHP also provides ltrim and rtrim for left‑only or right‑only trimming.
Understanding and using trim (as well as ltrim and rtrim ) makes string handling in PHP more efficient and helps improve development productivity.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.