Strings4 min readExamples run on PHP 8.5.10

trim()

Learn how PHP trim() removes whitespace or a custom set of characters from the start and end of a string, and why it leaves the middle alone.

Signature

trim(string $string, string $characters = " \n\r\t\v\x00"): string

Syntax

trim() returns a new string with unwanted characters removed from the beginning and end of $string. The original value is not changed.

Default behavior

Without a second argument, trim() removes these characters:

  • an ordinary space (" ")
  • a tab ("\t")
  • a line feed ("\n")
  • a carriage return ("\r")
  • a vertical tab ("\v")
  • the NUL byte ("\0")

This makes it a good first step when cleaning text that came from a form field, a line of text, or any other loosely formatted input.

Example
<?php
$text = "\t  Hello, PHP!  \n";
$clean = trim($text);
var_dump($clean);
Output
string(11) "Hello, PHP!"

The tab, spaces and newline around the text are removed. Whitespace between words is left untouched.

Custom character lists

The optional $characters argument is a list of individual characters, not a substring. trim() keeps removing any character from the list at either end until it reaches one that is not in the list.

You can also write a range with .., for example "\x00..\x1F" for the ASCII control characters.

When you pass your own list, the default whitespace characters are no longer included unless you list them too.

Example
<?php
$path = "//docs/php//";
var_dump(trim($path, "/"));

$hello = "Hello World";
var_dump(trim($hello, "Hdle"));

var_dump(trim("abc", "bad"));
var_dump(trim("abc", "b"));
Output
string(8) "docs/php"
string(5) "o Wor"
string(1) "c"
string(3) "abc"

The last two calls show a common surprise. In trim("abc", "bad"), the a is removed first, which puts b at the start so it is removed too. Only c remains. In trim("abc", "b"), the first and last characters are a and c, which are not in the list, so nothing is removed.

  • ltrim() removes characters from the start only.
  • rtrim() removes characters from the end only.
  • str_replace() is the tool to use when you need to remove characters from the middle of a string.
  • To clean every element of an array, apply trim() to each value, for example with array_map('trim', $values).
  • trim() works on bytes, so it does not treat multibyte whitespace such as a non-breaking space as whitespace by default.

Tested examples

Trim default whitespace
<?php
$text = "\t  Hello, PHP!  \n";
$clean = trim($text);
var_dump($clean);
Output
string(11) "Hello, PHP!"
Trim a custom character list
<?php
$path = "//docs/php//";
var_dump(trim($path, "/"));

$hello = "Hello World";
var_dump(trim($hello, "Hdle"));

var_dump(trim("abc", "bad"));
var_dump(trim("abc", "b"));
Output
string(8) "docs/php"
string(5) "o Wor"
string(1) "c"
string(3) "abc"