Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP trim() Function

PHP trim() Function

PHP String Reference Manual PHP String Reference Manual

Example

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

Run Example »


Definition and Usage

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

Related functions:


Syntax

trim(

string,charlist

)

Parameters 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, charlist parameter was added.

    More examples

    Example 1

    Remove spaces from both sides of a string:

    " ; 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 the newline character (\n) from both sides of a string:

    " ; 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 Reference Manual PHP String Reference Manual