PHP 8.6: trim, ltrim, rtrim, chop functions now trim Form-Feed (\f) by default
PHP supports trim, ltrim, rtrim, and rtrim alias chop functions that can trim white-spaces or other characters from the beginning, end, or both the beginning and the end of a given string.
All of these functions support a second parameter named $characters, which is set by default to a list of commonly trimmed characters:
trim(string $string, string $characters = " \n\r\t\v\x00"): string
Note that although
$charactersis set to a single string, it works as a character mask, trimming all characters set in the string.
| Character | Character name | ASCII Hex number |
|---|---|---|
" " |
Space | 0x20 |
"\n" |
Line-feed | 0x0A |
"\r" |
Carriage Return | 0x0D |
"\t" |
Horizontal Tab | 0x09 |
"\v" |
Vertical Tabulation | 0x0B |
"\0" |
NUL | 0x00 |
A notable character missing from this list is the Form-Feed character ("\f"), with ASCII number 0x0C.
Since PHP 8.6 and later, the default $characters parameter for all of the functions listed below are updated to include the Form-Feed character as well:
Accordingly, the function synopses have been updated as follows:
- trim(string $string, string $characters = " \n\r\t\v\x00"): string
+ trim(string $string, string $characters = " \f\n\r\t\v\x00"): string
Below is the complete list of characters trimmed by default with these functions:
| Character | Character name | ASCII Hex number |
|---|---|---|
" " |
Space | 0x20 |
"\f" |
Form-Feed | 0x0C |
"\n" |
Line-feed | 0x0A |
"\r" |
Carriage Return | 0x0D |
"\t" |
Horizontal Tab | 0x09 |
"\v" |
Vertical Tabulation | 0x0B |
"\0" |
NUL | 0x00 |
Backward Compatibility Impact
Since PHP 8.6 and later, trim, ltrim, rtrim and chop calls that do not pass the $characters parameter will trim the Form-Feed character as well as the previous list of trimmed characters.
These functions are typically used to remove excess spaces and new lines from a user-provided string, a text file, or otherwise a string taken from elsewhere, and trimming the Form-Feed character in addition to the other characters is deemed desirable.
Applications that need to intentionally preserve the Form-Feed characters when calling these functions must now pass the $characters parameter to make sure these functions behave identically across all PHP versions. This is not recommended unless the application needs to preserve Form-Feed characters.
- trim($string);
+ trim($string, characters: " \n\r\t\v\x00");