How can I strip / remove all spaces of a string in PHP?
I have a string like $string = "this is my string";
The output should be "thisismystring"
How can I do that?
The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: 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.
Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.
If you are just dealing with excess whitespace on the beginning or end of the string you can use trim() , ltrim() or rtrim() to remove it. If you are dealing with extra spaces within a string consider a preg_replace of multiple whitespaces " "* with a single whitespace " " .
Do you just mean spaces or all whitespace?
For just spaces, use str_replace:
$string = str_replace(' ', '', $string);
For all whitespace (including tabs and line ends), use preg_replace:
$string = preg_replace('/\s+/', '', $string);
(From here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With