trim
Removes whitespace and other characters from both ends of a string.
Available since: PHP 4
Syntax
trim(string $string, string $characters = " \n\r\t\v\x00"): stringParameters
| Parameter | Type | Description |
|---|---|---|
| $string | string | The source string. |
| $characters | string | Which characters to strip. By default: space, line break, tab and other whitespace. |
Return value
stringThe string without the given characters at its ends.
Examples
Stripping spaces and a line break:
<?php
var_dump(trim(" text \n"));Output:
string(4) "text"Stripping custom characters:
<?php
echo trim('--title--', '-');Output:
titleltrim() strips only the start, rtrim() only the end:
<?php
var_dump(ltrim(' text '));
var_dump(rtrim(' text '));Output:
string(6) "text "
string(6) " text"Notes
The function leaves characters inside the string alone — only the ends are stripped. Form input is worth passing through trim() before validating and saving.
See also
- str_replace — Replaces all occurrences of a substring with another string.
Related recipes
- How to check if a string is empty
- How to count words in a string
- How to get form data
- How to get the visitor's IP address
- How to remove all whitespace from a string
- How to remove empty values from an array
- How to remove the last character from a string
- How to trim whitespace from a string
- How to turn a string into a URL slug
- How to validate an email address
In the tutorial
- Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.