Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can strip whitespaces in PHP's variable?

I know this comment PHP.net. I would like to have a similar tool like tr for PHP such that I can run simply

tr -d " " "" 

I run unsuccessfully the function php_strip_whitespace by

$tags_trimmed = php_strip_whitespace($tags); 

I run the regex function also unsuccessfully

$tags_trimmed = preg_replace(" ", "", $tags); 
like image 241
Léo Léopold Hertz 준영 Avatar asked Aug 14 '09 19:08

Léo Léopold Hertz 준영


People also ask

Which function is used for removing whitespaces from?

strip(): The strip() method is the most commonly accepted method to remove whitespaces in Python. It is a Python built-in function that trims a string by removing all leading and trailing whitespaces.

How do I strip whitespace characters from other strings?

The trim() function in PHP removes whitespace or any other predefined character from both the left and right sides of a string. ltrim() and rtrim() are used to remove these whitespaces or other characters from the left and right sides of the string.

Which function removes whitespace from string?

trim() method removes the leading and trailing spaces present in the string. strip method removes the leading and trailing spaces present in the string. Also, it is Uniset/Unicode character aware.

Which method removes whitespace from both ends?

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).


1 Answers

To strip any whitespace, you can use a regular expression

$str=preg_replace('/\s+/', '', $str); 

See also this answer for something which can handle whitespace in UTF-8 strings.

like image 86
Paul Dixon Avatar answered Sep 23 '22 12:09

Paul Dixon