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"