Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

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"): string

Parameters

ParameterTypeDescription
$stringstringThe source string.
$charactersstringWhich 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:

title

ltrim() 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

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.