In PHP, the trim() function is used to remove whitespace and other predefined characters from the beginning and end of a string.
Syntax:
trim(string $string, string $characters = " \n\r\t\v\0"): string
- $string: The input string.
- $characters (optional): A list of characters to strip (default: whitespace, newline, tab, etc.)
Common Examples
1. Remove whitespace from start and end
$text = " Hello World! ";
$trimmed = trim($text);
echo $trimmed; // Output: "Hello World!"
2. Remove specific characters
$text = "###PHP###";
$cleaned = trim($text, "#");
echo $cleaned; // Output: "PHP"
3. Remove multiple characters
$text = "++--Hello--++";
$cleaned = trim($text, "+-");
echo $cleaned; // Output: "Hello"
4. Remove newline, tabs, etc.
$text = "\n\t Hello World \r\n";
echo trim($text); // Output: "Hello World"
Related Functions
ltrim() – Removes characters only from the beginning (left side).
rtrim() – Removes characters only from the end (right side).
echo ltrim(" Hello"); // "Hello"
echo rtrim("World "); // "World"