The trim() function in PHP removes whitespace and other predefined characters from both sides of a string.Here’s how it works in PHP 8, PHP 8.1, PHP 8.2, PHP 8.3 and PHP 8.4.
Syntax
trim(string $string, string $characters = " \t\n\r\0\x0B"): string
Parameters
$string: The input string
$characters (optional): Specifies which characters to remove (default removes whitespace characters)
Common Whitespace Characters
” ” – ordinary space
“\t” – tab
“\n” – new line
“\r” – carriage return
“\0” – NULL byte
“\x0B” – vertical tab
Examples
1. Basic Usage (removing spaces)
$str = " Hello World! "; echo trim($str); // Outputs: "Hello World!"
2. Removing Specific Characters
$str = "Hello World!"; echo trim($str, "Hed!"); // Outputs: "llo Worl"
3. Removing Multiple Types of Whitespace
$str = "\t\tHello World!\n\n"; echo trim($str); // Outputs: "Hello World!"
4. Trimming Specific Characters from Both Ends
$str = "ABCHello World!CBA"; echo trim($str, "ABC"); // Outputs: "Hello World!"
5. Real-world Example (form input)
$username = " user123 "; $clean_username = trim($username); // Now $clean_username is "user123" without spaces
Related Functions
ltrim() – Remove characters from the left side only.
rtrim() – Remove characters from the right side only.
The trim() function is particularly useful when processing user input from forms to remove accidental whitespace.