PHP trim()Functions

PHP String 参考手册PHP String Reference Manual

Examples

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

<?php $str = "Hello World!"; echo $str . PHP_EOL; 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 and other predefined characters from the left side of a string.
  • rtrim() - Removes whitespace and 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 this parameter is omitted, all of the following characters are removed:
  • "\0" - NULL
  • "\t" - Tab
  • "\n" - Newline
  • "\x0B" - Vertical tab
  • "\r" - Carriage return
  • " " - Space

Technical Details

Return value: Returns the modified string.
PHP version: 4+
Changelog: In PHP 4.1, thecharlistparameter was added.


More Examples

Example 1

Remove spaces 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 above code is as follows (view source):

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

The browser output of the above code is as follows:

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

Run Example »

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); ?>

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

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

The browser output of the above code is as follows:

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

Run Example »


PHP String 参考手册PHP String Reference Manual Other Extensions