Current Location: Home> Function Categories> trim

trim

Remove spaces (or other characters) from the beginning and end of the string
Name:trim
Category:String
Programming Language:php
One-line Description:Removes whitespace characters and other characters on both sides of the string.

Definition and usage

The trim() function removes whitespace characters or other predefined characters on both sides of the string.

Related functions:

  • ltrim() - Removes whitespace or other predefined characters to the left of the string
  • rtrim() - Removes whitespace or other predefined characters to the right of the string

Example

Example 1

Remove characters on both sides of the string ("He" in "Hello" and "d!" in "World"):

 <?php
$str = "Hello World!" ;
echo $str . "<br>" ;
echo trim ( $str , "Hed!" ) ;
?>

Try it yourself

Example 2

Remove spaces on both sides of the string:

 <?php
$str = " Hello World!" ;
echo "Don't use trim: " . $str ;
echo "<br>" ;
echo "Use trim: " . trim ( $str ) ;
?>

The HTML output of the above code is as follows (please check the source code):

 < ! DOCTYPE html >
< html >
< body >

Don't use trim : Hello World ! < br > Use trim : Hello World !
< / body >
< / html >

The browser output of the above code is as follows:

 Don't use trim: Hello World!
Use trim: Hello World!

Try it yourself

Example 3

Remove the newline character (\n) on both sides of the string:

 <?php
$str = "\n\n\n\nHello World!\n\n\n" ;
echo "Don't use trim: " . $str ;
echo "<br>" ;
echo "Use trim: " . trim ( $str ) ;
?>

The HTML output of the above code is as follows (please check the source code):

 < ! DOCTYPE html >
< html >
< body >

Don't use trim :


Hello World !


< br > Use trim : Hello World !
< / body >
< / html >

The browser output of the above code is as follows:

 Don't use trim: Hello World!
Use trim: Hello World!

Try it yourself

grammar

 trim ( string , charlist )
parameter describe
string Required. Specifies the string to be checked.
charlist

Optional. Specifies which characters to delete from the string. If omitted, all the following characters are removed:

  • "\0" - NULL
  • "\t" - Tab
  • "\n" - Line break
  • "\x0B" - Vertical tab character
  • "\r" - Enter
  • " " - Spaces
Similar Functions
Popular Articles