What does trim() do?
trim() removes characters from the beginning and end of a string. By default it strips spaces, tabs, newlines, carriage returns, NUL bytes and vertical tabs. ltrim() only trims the left side and rtrim() only the right.
Syntax
trim(string $string, string $characters = " \n\r\t\v\x00"): string
Parameters
$string- The string to trim.$characters- Optional list of characters to strip. It is a set of characters, not a substring; ranges like"a..z"are allowed.
Return value
The trimmed string. Characters in the middle of the string are never removed.
trim() examples
Every example below shows the exact output it produces. Paste any of them into the editor above (or the online compiler) to run it.
1. trim(), ltrim() and rtrim()
<?php
$input = " hello world \n";
var_dump(trim($input));
var_dump(ltrim($input));
var_dump(rtrim($input));
Output:
string(11) "hello world" string(14) "hello world " string(14) " hello world"
2. Strip custom characters
<?php
echo trim("--Hello--", "-") . "\n";
echo trim("/path/to/dir/", "/") . "\n";
echo rtrim("1.5000", "0") . "\n";
echo trim("abcHelloabc", "a..c") . "\n";
Output:
Hello path/to/dir 1.5 Hello
3. Clean an array of form values
<?php
$tags = [" php ", "html ", " css"];
$clean = array_map('trim', $tags);
echo implode(",", $clean) . "\n";
// Collapse internal whitespace too
echo preg_replace('/\s+/', ' ', trim(" too many spaces ")) . "\n";
Output:
php,html,css too many spaces
Common mistakes and gotchas
- Character set, not substring:
trim("abcxa", "abc")returns "x" because every leading/trailing a, b or c is removed. To remove a prefix, usestr_starts_with()+substr(). - Inner whitespace: trim never touches the middle of a string; use
preg_replace('/\s+/', ' ', $s)for that. - Non-breaking spaces: a UTF-8 non-breaking space (
\xC2\xA0) is not in the default list; usepreg_replace('/^\s+|\s+$/u', '', $s).