trim – PHP String Functions
Syntax :
Description :
trim() function will truncate spaces or other characters from the beginning and end of input string. It will remove “hi” from starting and “es.” from the end of input string “hi from tutorialmines.”.
Parameter :
- string – This is a Required parameter. This is a string on which function will be performed.
- charlist – This is a Optional parameter. The stripped characters can also be specified using the charlist parameter. You have to write down all characters which you want to be stripped. With .. you can specify a range of characters.
The following characters are removed if the charlist parameter is empty:
- “\0” – NULL
- “\t” – tab
- “\n” – new line
- “\r” – carriage return
- ” ” – ordinary white space
- “\x0B” – vertical tab
Output :
This will return a trimmed string.
Related articles : rtrim(), ltrim().
trim() – PHP Functions Example 1 :
<?php // below statement will trim white spaces from both sides of string." $strExample = " Hi from tutorialmines. "; echo trim($strExample); ?>
In above example ,We have a string ” Hi from tutorialmines. “. Now this function will trim blank spaces from both side of string. Output of above code in the browser is as below:
trim() – PHP Functions Example 2 :
<?php // below statement will trim white spaces from both sides of string." $strExample = " \nHi from \ntutorialmines.\n\n "; echo trim($strExample); ?>
In above example ,We have a string ‘ \nHi from \ntutorialmines.\n\n ‘. Now this function will trim blank spaces,\n character from both side of string. Output in ViewSource of browser is below ( HTML output of the code above):
<html><head></head><body> Hi from tutorialmines. </body></html>
See below is the output of above code.
trim() – PHP Functions Example 3 : Using .. you can specify a range of characters.
<?php $strExample = "Hi from tutorialmines. This is a example of trim() function. Testing parameter"; echo trim($strExample,"Hi..parameter"); ?>
In above example ,We have a string ‘Test Hi from tutorialmines. This is a example of trim() function. Testing parameter’. Now this function remove “Test ” from the starting and “parameter” from the end of string. See below is the output of above code.
from tutorialmines. This is a example of trim() function. Testing