trim
Removes whitespace or other given characters from both ends of a string.
trim(string $string, string $characters = " \n\r\t\v\x00"): string- Added in PHP 4.0
Parameters
| Parameter | Type | Description |
|---|---|---|
$string | string | The string that will be trimmed. |
$charactersoptional | string= " \n\r\t\v\x00" | The set of characters to strip. Each character is treated individually; ranges may be written with '..', as in 'a..z'. |
Return value
stringThe string with the given characters stripped from both ends.
Errors
Does not throw. An invalid '..' range in the characters argument emits an E_WARNING ("Invalid '..'-range") and the malformed range is not applied.
trim strips characters from both ends of a string and stops at the first character that is not in the set. By default that set is space, tab, newline, carriage return, vertical tab and NUL — the six bytes that ordinarily represent "nothing" in ASCII text.
When to reach for it
Trimming form input before validation is the standard use; a required field containing only spaces should fail, and only trim makes that visible. It is equally useful for normalising lines read from a file, where the trailing \n would otherwise end up in your data, and for stripping known delimiters — trim($path, '/') is the cleanest way to normalise a URL segment.
What trips people up
The second argument is a character set, not a suffix. trim('xoxo', 'xo') strips every leading and trailing x or o and returns an empty string, which surprises people expecting a single removal.
Passing custom characters also replaces the default whitespace set rather than adding to it, so trim($s, '/') leaves spaces alone. And trim knows nothing about Unicode: a non-breaking space (\xC2\xA0) pasted from a browser survives untouched, which is a frequent source of "but the field looks empty" bug reports.
Example
When to use it
- Clean submitted form fields before validating that a required value is actually present.
- Strip the trailing newline from lines read out of a file or a stream.
- Normalise a URL path segment by removing leading and trailing slashes.
- Remove surrounding quote characters from a value parsed out of a config line.
Frequently asked questions
What is the difference between trim, ltrim and rtrim?
trim strips from both ends, ltrim only from the left and rtrim only from the right. All three take the same optional character-set argument.
Why does trim not remove a non-breaking space?
trim only removes the bytes you list, and the default list is ASCII whitespace plus NUL. A UTF-8 non-breaking space is the two bytes 0xC2 0xA0, which are not in that set — remove it with a preg_replace using the /u modifier.
Does trim remove characters from inside the string?
No, only from the ends. It stops at the first character not in the set, so 'a b' keeps its inner space; use str_replace or preg_replace to strip interior whitespace.
More examples
Validating a required field
Prints "name: 'Ada'", 'bio: MISSING' and "city: 'Paris'". Without the trim, the bio field of pure whitespace would pass a naive empty() check and store an invisible value.
<?php
$fields = ['name' => ' Ada ', 'bio' => " \n\t ", 'city' => 'Paris'];
foreach ($fields as $key => $raw) {
$value = trim($raw);
echo $key, ': ', $value === '' ? 'MISSING' : "'$value'", "\n";
}trim versus ltrim and rtrim
The last line prints string(0) "" — every character of 'xoxo' is in the set {x, o}, so trimming eats the whole string. That is the behaviour that catches people who expect a single 'xo' to be removed.
<?php
$s = '...core...';
echo trim($s, '.'), "\n"; // core
echo ltrim($s, '.'), "\n"; // core...
echo rtrim($s, '.'), "\n"; // ...core
// The set is characters, not a suffix:
var_dump(trim('xoxo', 'xo'));
Discussion