PHP

 Home  Computers & Internet  Web Programming PHP
What is PHP?
Echo
Comments
Variables
Constants
Data Types
number_format()
Character Strings
Mathematical Operators
Comparison Operators
Logical Operators
Joining Strings
explode()
implode()
strtolower()
strtoupper()
strlen()
ucfirst()
ucwords()
strrev()
str_replace()
str_repeat()
trim()
strip_tags()
addslashes()
stripslashes()
strpos()
strrpos()
nl2br()
isset()
unset()
empty()
POST
GET
If Statements
If Else Statements
Elseif Statements
Switch Statements
For Loops
While Loops
Do While Loops
Foreach Loops
File Create
File Open
File Read
File Write
File Delete
fgets()
file_get_contents()
Date & Time
$_SERVER
Sessions
Cookies
Arrays

HOW TO USE THE trim() FUNCTION IN PHP

The trim() function strips specified characters from beginning and end of a string. It takes two parameters: the string to perform the action on and the specified character/s to strip out from the beginning and end of that string.

If the characters to strip are not specified, then trim() strips all whitespace (" "), new line "\n", tab ("\t"), carriage return ("\r") by default.

Example:

$string=" John James was here ";
$newstring=trim($string);

echo $newstring;

The above will output: John James was here

This is a good function to use when, for example, a user enters something in the input field of a site form but mistakenly leaves a whitespace before the actual entry. Technically, whitespace John is not the same as John as whitespace is considered a character as well.

You can also specify what character/s to strip from the beginning and end of a string.

Example:

$string="eggs sold here";
$newstring=trim($string,"e");

echo $newstring;

The above will output: ggs sold her
The e at the beginning of the string and the e at the end of the string are stripped out.

Say you only want to strip the e at the right (ie. at the end of the string), then use:

$string="eggs sold here";
$newstring=rtrim($string,"e"); // right trim

echo $newstring;

The above will output: eggs sold her

Say you only want to strip the e at the left (ie. at the start of the string), then use:

$string="eggs sold here";
$newstring=ltrim($string,"e"); // left trim

echo $newstring;

The above will output: ggs sold here

Home | Privacy Policy | Terms Of Use | Contact Us