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.
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()
<code>string trim(string $str, string $character_mask = " \t\n\r\0\x0B")</code>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() :
<code>$str = " Hello, World! ";
echo "Original string: '" . $str . "'";
echo "Trimmed string: '" . trim($str) . "'";
</code>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:
<code>$str = "XOXHello, World!OXOX";
echo "Original string: '" . $str . "'";
echo "Trimmed string: '" . trim($str, "XO") . "'";
</code>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.
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.