The trim Function

The trim function removes whitespace from the beginning and end of a string. It can also remove other characters if specified as the second parameter.

Syntax

phptrim(string $string, string $characters = " \t\n\r\0\x0B"): string

Example

Let's remove whitespace from the edges of the string:

php<?php
  echo(trim(' abcde '));
?>

Code execution result:

php'abcde'

Example

Let's remove slashes from the edges of the string:

php<?php
  echo trim('/abcde/', '/');
?>

Code execution result:

php'abcde'

Example

Let's remove slashes and dots from the edges of the string:

php<?php
  echo trim('/abcde.', '/.');
?>

Code execution result:

php'abcde'

Example

The function removes any number of specified characters if they are on the edge:

php<?php
  echo trim('../../abcde...', '/.');
?>

Code execution result:

php'abcde'

Example

A range of characters can be specified using two dots '..'. For example, let's specify that we want to remove characters from 'a' to 'd':

php<?php
  echo trim('abcde', 'a..d');
?>

Code execution result:

php'e'

See Also

  • the ltrim function,
    which removes whitespace from the left
  • the rtrim function,
    which removes whitespace from the right