Using PHP trim() Function to Remove Whitespace and Specific Characters
This article explains how the PHP trim() function removes leading and trailing whitespace from strings, demonstrates basic and advanced usage with code examples, and shows how to specify custom characters for more precise string cleaning.
The PHP trim function is a useful string‑handling utility that removes whitespace characters (spaces, tabs, newlines, etc.) from both ends of a string, helping developers obtain clean input and avoid errors caused by irregular user data.
Below is a simple example that defines a string with surrounding spaces, applies trim($str) , and echoes both the original and trimmed strings.
<?php
$str = " Hello, World! ";
$trimmed_str = trim($str);
echo "Original string: " . $str . "";
echo "
";
echo "String after trimming: " . $trimmed_str . "";
?>The code first creates $str containing leading and trailing spaces, then calls trim($str) to produce $trimmed_str . The echo statements display the before and after results.
Running the script yields the following output:
Original string: " Hello, World! "
String after trimming: "Hello, World!"Beyond the basic usage, trim accepts a second argument that specifies a set of characters to strip. The example below removes the characters H , d , and ! from the string.
<?php
$str = "Hello, World!";
$trimmed_str = trim($str, "Hd!");
echo "Original string: " . $str . "";
echo "
";
echo "String after removing 'H', 'd', '!': " . $trimmed_str . "";
?>In this case the second parameter "Hd!" tells trim to also strip those characters, resulting in the output:
Original string: "Hello, World!"
String after removing 'H', 'd', '!': "ello, Worl"Thus, by providing a custom character mask, developers can achieve more precise string manipulation. In summary, the PHP trim function efficiently cleans whitespace and, when needed, specific characters, improving the stability and security of PHP applications.
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.