Trim functions help remove unwanted spaces or characters from the start and end of text. This makes the text clean and ready to use.
Trim functions in PHP
trim(string $str, string $characters = " \t\n\r\0\x0B"): string ltrim(string $str, string $characters = " \t\n\r\0\x0B"): string rtrim(string $str, string $characters = " \t\n\r\0\x0B"): string
trim() removes characters from both ends of the string.
ltrim() removes characters only from the start (left side).
rtrim() removes characters only from the end (right side).
$text = " hello "; $clean = trim($text); echo "'$clean'";
$text = "***hello***"; $clean = trim($text, "*"); echo "'$clean'";
$text = " hello "; $cleanLeft = ltrim($text); echo "'$cleanLeft'";
$text = " hello "; $cleanRight = rtrim($text); echo "'$cleanRight'";
This program shows how trim(), ltrim(), and rtrim() work on a string with spaces and special characters. It also shows removing custom characters like asterisks.
<?php // Example showing trim functions $input = " \tHello World!\n "; echo "Original: '" . $input . "'\n"; $trimmed = trim($input); echo "Trimmed: '" . $trimmed . "'\n"; $leftTrimmed = ltrim($input); echo "Left Trimmed: '" . $leftTrimmed . "'\n"; $rightTrimmed = rtrim($input); echo "Right Trimmed: '" . $rightTrimmed . "'\n"; // Using trim to remove custom characters $custom = "***Hello***"; $customTrimmed = trim($custom, "*"); echo "Custom Trimmed: '" . $customTrimmed . "'\n"; ?>
By default, trim removes spaces, tabs, new lines, and some other whitespace characters.
You can specify which characters to remove by passing them as the second argument.
Trim functions do not change the original string; they return a new trimmed string.
Trim functions clean text by removing unwanted characters from the start and/or end.
Use trim() for both ends, ltrim() for left only, and rtrim() for right only.
They help prepare text for storage, comparison, or display.