Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I strip all spaces out of a string in PHP? [duplicate]

Tags:

string

php

spaces

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?

like image 487
streetparade Avatar asked Jan 21 '10 13:01

streetparade


People also ask

How do I strip whitespace in PHP?

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.

How do I remove all spaces between strings?

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.

How do I get rid of extra white spaces in a string?

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 " " .


1 Answers

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).

like image 172
Mark Byers Avatar answered Sep 29 '22 09:09

Mark Byers