PHP trim() Function
The trim() function removes whitespace (or other characters) from both ends of a string.
Syntax
trim(string $string, string $characters = " \n\r\t\v\x00"): string
Parameters
| Parameter | Type | Description |
|---|---|---|
$string | string | The string to trim |
$characters | string | Characters to remove (optional) |
Return Value
Returns the trimmed string.
Try It Online
Output
Click Run to execute your code
More Examples
Basic Whitespace Removal
<?php
$str = " Hello World ";
echo "[" . trim($str) . "]";
// "[Hello World]"
?>
Left/Right Trim
<?php
$str = " Hello ";
echo ltrim($str); // "Hello " (left only)
echo rtrim($str); // " Hello" (right only)
?>
Custom Characters
<?php
$str = "###Hello###";
echo trim($str, "#"); // "Hello"
?>
Tip: Always trim user input before storing or comparing to avoid whitespace issues.
Common Use Cases
- Cleaning form input
- Normalizing strings for comparison
- Removing BOM characters
- Processing file content
Related Functions
ltrim()- Trim left side onlyrtrim()- Trim right side only- str_replace() - Replace characters
Enjoying these tutorials?