PHP trim() function

Example

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

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

Run Instances

Definition and Usage

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

Related Functions:

  • ltrim() - Remove whitespace characters or predefined characters from the left side of the string
  • rtrim() - Remove whitespace characters or predefined characters from the right side of the string

Syntax

trim(s
tring,charlist)
Parameter Description
string Mandatory. Specifies the string to be checked.
charlist

Optional. Specifies which characters to remove from the string. If omitted, the following characters are removed:

  • "\0" - NULL
  • "\t" - Tab
  • "\n" - New Line
  • "\x0B" - Vertical Tab
  • "\r" - Carriage Return
  • " " - Space

Technical Details

Return value: Returns the modified string
PHP Version: 4+
Update Log: In PHP 4.1, a new feature was added: charlist Parameter.

More Examples

Example 1

Remove spaces from both sides of the string:

<?php
$str = " Hello World! ";
echo "Do not use trim: " . $str;
echo "<br>";
echo "Use trim: " . trim($str);
?>

The HTML output of the above code is as follows (please check the source code):

<!DOCTYPE html>
<html>
<body>
Do not use trim:  Hello World! <br>Use trim: Hello World!
</body>
</html>

The browser output of the above code is as follows:

Do not use trim: Hello World!
Use trim: Hello World!

Run Instances

Example 2

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

<?php
$str = "\n\n\nHello World!\n\n\n";
echo "Do not use trim: " . $str;
echo "<br>";
echo "Use trim: " . trim($str);
?>

The HTML output of the above code is as follows (please check the source code):

<!DOCTYPE html>
<html>
<body>
Do not use trim:
Hello World!
<br>Use trim: Hello World!
</body>
</html>

The browser output of the above code is as follows:

Do not use trim: Hello World!
Use trim: Hello World!

Run Instances