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"
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.