trim() Function Use in PHP 8.4 and PHP 8.5

The trim() function behaves identically in PHP 8.4 and PHP 8.5. There are no version-specific changes for this function in either release. The only recent changelog entry for trim() is in PHP 8.6.0, which adds the form feed character (f) to the default character list.

Function

trim() removes whitespace (or other specified characters) from both the beginning and end of a string .

Signature:

trim(string $string, string $characters = " vx00"): string

Default Characters Removed: Without a custom character list, trim()strips these ASCII characters :

  • " " (space).
  • " " (tab).
  • " " (newline).
  • " " (carriage return).
  • "" (NUL byte).
  • "v" (vertical tab).

Example

A common use case is cleaning up user input that may have accidental spaces:

<?php
$input = "  Hello World!  ";

// Remove the surrounding spaces
$clean = trim($input);

echo $clean; // Outputs: "Hello World!"
?>

Custom Character Example

You can specify exactly which characters to strip. This example removes slashes from a path:

<?php
$path = "/var/www/html/";

// Remove the "/" from both ends
$cleanPath = trim($path, "/");

echo $cleanPath; // Outputs: "var/www/html"
?>

You can also use .. to specify a range of characters, such as stripping all ASCII control characters.

23 Views