PHP 8 reference · String Functions

PHP trim() Function

Remove whitespace (or other characters you choose) from both ends of a string. Spaces inside the string are kept.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

trim(string $string, string $characters = " \n\r\t\v\x00"): string

Parameters

ParameterDescription
string The input string.
characters optional The characters to strip. Use .. for a range, as in "a..z". Default: " \n\r\t\v\x00"

Return value

The trimmed string.

Examples

Clean form inputTry it yourself
<?php
$input = "   [email protected] \n";
var_dump(trim($input));

Output

string(15) "[email protected]"
Strip other charactersTry it yourself
<?php
echo trim("--==Title==--", "-="), "\n";
echo trim("/path/to/dir/", "/"), "\n";

Output

Title
path/to/dir

Common mistakes

  • The second argument is a set of characters, not a string to remove: trim("hello", "ho") gives "ell".
  • A non-breaking space (U+00A0) isn't stripped by default. Use mb_trim() (PHP 8.4+) or preg_replace('/^\s+|\s+$/u', '', $text).

Version history

VersionChange
PHP 4.0Added

In other languages

Was this page helpful?