PHP String trimming Functions
PHP has four functions to perform the trimming functionality on string.
Below are the functions for trimming operation on string.
- trim()
- ltrim()
- rtrim()
- chop()
Lets get into each one.
trim()
This function will remove the white space ( or specified chars in second arguments ) from the beginning and ending of the string.
If we do not pass the second argument then it will remove the below character from the begining and ending of the string.
- ” ” , blank space
- “\t”, a tab
- “\n”, a new line
- “\r”, a carriage return
- “\0″, the NUL-byte
- “\x0B”, a verticle tab
This function takes two arguments.
string
This is the string which needs to be trimmed.
char list (optional)
We can pass the list of characters which we want this function to remove also.
Note: With .. you can specify a range of characters.
Usage:
<?php echo trim(' Hello '); // Hello echo trim('Hello Hi', 'Hi'); // ello ?>
ltrim()
This function is same as trim() but it removes white spaces and other specified characters from the beginning of the string.
Also this functions takes same arguments as trim().
rtrim()
This function is same as trim() but it removes white spaces and other specified characters from the ending of the string.
Also this functions takes same arguments as trim();
chop()
This function is an alias of the rtrim().
More From Avinash
Avinash Recommends
- PHP for Android (refulzphp)
- Important String Functions in PHP – Capitalization (refulzphp)
