PHP | trim() Function

The trim() function in PHP is an inbuilt function which removes whitespaces and also the predefined characters from both sides of a string that is left and right.

Related Functions:

Syntax:



trim($string, $charlist)

Parameters:The function accepts one mandatory parameter and one optional parameter as shown in the above syntax and described below.

  1. $string: This parameter specifies the string from which the whitespace and predefined characters from left and right are to be removed
  2. $charlist: This is an optional parameter which specifies the characters that are to be removed from the string. If this is not mentioned then all of the following characters will be removed:
    • “\0” – NULL
    • “\t” – tab
    • “\n” – new line
    • “\x0B” – vertical tab
    • “\r” – carriage return
    • ” ” – ordinary white space

Return Value: It returns the modified string by removing the whitespace and also the predefined characters from both sides of a string that is left and right.

Below programs illustrate the trim() function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to demonstrate the use of trim() 
// function when second parameter is present
  
// removes the predefined characters from 
// front and back 
$str = "Hello World!";
echo trim($str, "Hell!");
?>

chevron_right


Output:

o World

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to demonstrate the use of trim() 
// function when second parameter is absent
  
$str = "  geeks for geeks ";
  
// removes all leading and trailing whitespaces 
echo trim($str);
?>

chevron_right


Output:

geeks for geeks

Reference: http://php.net/manual/en/function.trim.php



My Personal Notes arrow_drop_up

Contented with little yet wishing for more

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.