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
Syntax
trim(string $string, string $characters = " \n\r\t\v\x00"): string
Parameters
| Parameter | Description |
|---|---|
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
<?php
$input = " [email protected] \n";
var_dump(trim($input));
Output
string(15) "[email protected]"
<?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+) orpreg_replace('/^\s+|\s+$/u', '', $text).
Version history
| Version | Change |
|---|---|
| PHP 4.0 | Added |
In other languages
str.strip()· Pythonstring.trim()· JavaScript
Related
ltrim()· Remove whitespace or other chosen characters from the start (left side) of a string only.rtrim()· Remove whitespace or other chosen characters from the end (right side) of a string. chop() is an alias.mb_trim()· Strip whitespace from both ends of a string, including Unicode spaces such as the non-breaking space. Added in PHP 8.4.- PHP Strings · tutorial