PHP trim() Function
Example
Remove characters from both sides of a string ("He" in "Hello" and "d!" in "World"):
<?php
$str = "Hello World!";
echo $str . "<br>";
echo trim($str,"Hed!");
?>
Run example »
Definition and Usage
The trim() function removes whitespace and other predefined characters from both sides of a string.
Related functions:
- ltrim() - Removes whitespace or other predefined characters from the left side of a string
- rtrim() - Removes whitespace or other predefined characters from the right side of a string
Syntax
trim(string,charlist)
Parameter | Description |
---|---|
string | Required. Specifies the string to check |
charlist | Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:
|
Technical Details
Return Value: | Returns the modified string |
---|---|
PHP Version: | 4+ |
Changelog: | The charlist parameter was added in PHP 4.1 |
More Examples
Example 1
Remove whitespaces from both sides of a string:
<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>
The HTML output of the code above will be (View Source):
<!DOCTYPE html>
<html>
<body>
Without trim: Hello World! <br>With trim: Hello World!
</body>
</html>
The browser output of the code above will be:
Without trim: Hello World!
With trim: Hello World!
Run example »
Example 2
Remove newlines (\n) from both sides of the string:
<?php
$str = "\n\n\nHello World!\n\n\n";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>
The HTML output of the code above will be (View Source):
<!DOCTYPE html>
<html>
<body>
Without trim:
Hello World!
<br>With trim: Hello World!
</body>
</html>
The browser output of the code above will be:
Without trim: Hello World!
With trim: Hello World!
Run example »
❮ PHP String Reference