What does the trim function do in Php?

The trim function removes white spaces and pre-defined characters from a string.

Syntax

The general syntax is :

trim(string, trim_string)
  • string is the actual string
  • trim_string contains the string to be removed from the string

Note: If the second parameter is not mentioned, all of the following characters are removed:

  • “\0” - NULL
  • “\t” - tab
  • “\n” - new line
  • “\x0B” - vertical tab
  • “\r” - carriage return
  • " " - ordinary white space

Implementation

Example 1

The following example does not specify the second parameter of the print function:

<?php
$str = " Educative is a website for learning new languages! ";
echo "String:".$str . "\n";
echo "Trimmed String:".trim($str);
?>

Example 2

The following example defined the string to be trimmed from the string:

<?php
$str = "Python Programming!";
$trim_str="Python";
echo "String:".$str . "\n";
echo "Trimmed String:".trim($str,$trim_str);
?>

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved