Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo trim("  hello  ");        // hello
echo trim("--hi--", "-");      // hi

Try it

PHP Whitespace and custom characters

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.

PHP Ranges, cleaning input and non-breaking spaces

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

PHP
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 of H, e, l from both ends and leaves "o". To remove a literal prefix or suffix, use str_starts_with() with substr().
  • 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 u modifier. PHP 8.4 adds mb_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 null to $string is deprecated since PHP 8.1.
  • Use trim() on user input before comparing or validating, but never as a substitute for escaping.