PHP Reference ยท String Functions
PHP trim() function
Reference for PHP trim(): strip whitespace or a custom set of characters from both ends of a string, including ranges, and learn what it does not remove.
trim() removes characters from the beginning and the end of a string. With no second argument it strips whitespace; with a second argument you decide exactly which characters to remove.
Only the ends are touched. Spaces between words stay, and the characters you list are removed as a set, not as a sequence. See ltrim() and rtrim() for one-sided versions.
<?php echo trim(" hello "); // hello echo trim("--hi--", "-"); // hi
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
trim(string $string, string $characters = " \n\r\t\v\x00"): string
| Name | Description |
|---|---|
$string |
The string to trim. |
$characters |
Optional list of characters to strip. A range can be written as a..z. |
Return value: the trimmed string. The original is unchanged.
Usage notes
- Default characters: space, tab (
\t), newline (\n), carriage return (\r), NUL byte (\0) and vertical tab (\v). Form feed (\f) is not included by default. - A set, not a prefix.
trim("Hello", "Hel")removes any ofH,e,lfrom both ends and leaves"o". To remove a literal prefix or suffix, usestr_starts_with()withsubstr(). - Bytes only. Multibyte whitespace such as the non-breaking space is not handled; trim its UTF-8 bytes explicitly or use a regex with the
umodifier. PHP 8.4 addsmb_trim()for this. - Trimming numbers:
trim("12.5000", "0")is a crude way to drop trailing zeros but also removes leading ones. - Always cast non-strings. Passing
nullto$stringis deprecated since PHP 8.1. - Use
trim()on user input before comparing or validating, but never as a substitute for escaping.
Related
ltrim(),rtrim(),str_replace(),preg_replace()- Lessons: Strings, String functions