Easy Tutorial
❮ Func Date Timezone Offset Get Func Filesystem Tmpfile ❯

PHP trim() Function

PHP String Reference Manual

Example

Remove characters from both sides of a string ("He" from "Hello" and "d!" from "World"):

<?php
$str = "Hello World!";
echo $str . PHP_EOL;
echo trim($str, "Hed!");
?>

Definition and Usage

The trim() function removes whitespace or other predefined characters from both sides of a string.

Related functions:


Syntax

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: "\0" - NULL<br> "\t" - Tab<br> "\n" - New line<br> "\x0B" - Vertical tab<br> "\r" - Carriage return<br> " " - Space

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 whitespace from both sides of a string:

<?php
$str = " Hello World! ";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>

HTML output of the above code (view source):

<!DOCTYPE html>
<html>
<body>

Without trim: Hello World! <br>With trim: Hello World!
</body>
</html>

Browser output of the above code:

Without trim: Hello World!
With trim: Hello World!

Example 2

Remove newline characters (\n) from both sides of a string:

<?php
$str = "nnnHello World!nnn";
echo "Without trim: " . $str;
echo "<br>";
echo "With trim: " . trim($str);
?>

HTML output of the above code (view source):

<!DOCTYPE html>
<html>
<body>

Without trim:


Hello World!


<br>With trim: Hello World!
</body>
</html>

Browser output of the above code:

Without trim: Hello World!
With trim: Hello World!

❮ Func Date Timezone Offset Get Func Filesystem Tmpfile ❯