PHP trim() or strip Function:
Definition and Usage:
The trim() function removes whitespace and other predefined characters from both sides of a string.
ltrim() – Removes whitespace or other predefined characters from the left side of a string
rtrim() – Removes whitespace or other predefined characters from the right side of a string
sample php program with ltrim() function
Its output will be :
how to remove blank spaces how:<br> to remove blank spaces how:<br>
program with rtrim()
Its output will be:
how to remove blank spaces how:<br>how to remove blank spaces :<br>
Here we can see that “how” is removed from end only, the beginning “how” remains in the ouput string .
We can use any of these function for remove the un necessary whitespaces or characters from the end or beginning or from both as per our requirement.And note trim() = rtrim() + ltrim() in action.
How to strip all spaces out of a string in php:
You have a string stored in a PHP variable, and you want to eliminate all whitespaces or spaces from that string with PHP, not only from the beginning or the end of the string.
Solution for spaces:
Solution for whitespaces:
Difference between spaces and whitespaces:
Space is the regular space character between words, whitespace is any kind of space in text: regular space, new line, tab, etc.
Their ASCII representation differs one from another, this is why we need different solutions for them.