PHP provides built-in string cleaning functions such as trim() and chop() to remove unwanted characters—mainly whitespace—from strings. These functions are essential when working with user input, form data, or formatted text.
trim() removes characters from both the beginning and end of a string.chop() is an alias of rtrim() and removes characters only from the right end.trim(string, characters)chop(string, characters)
// Removing whitespace from both ends of a string
<?php
$string = " Hello World! ";
$trimmed = trim($string);
echo $trimmed;
?>
The trim() function removes spaces from the beginning and end of the string, resulting in clean output without altering the inner content.
// Removing whitespace only from the right side
<?php
$string = "Hello World! ";
$chopped = chop($string);
echo $chopped;
?>
chop() removes only trailing spaces, keeping the left side unchanged.
// Removing specific characters from both ends
<?php
$string = "xxHello World!xx";
$trimmed = trim($string, "x");
echo $trimmed;
?>
Here, trim() removes the specified character x from both the beginning and end of the string.
Think of trim() as cleaning both sides of a word, while chop() cleans only the right side. These are commonly used before saving or validating user input.
trim() when handling form data.ltrim() if only left-side cleanup is required.ltrim() and rtrim().# or * from string edges.