How can strip whitespaces in PHP's variable?

Léo Léopold Hertz 준영 picture Léo Léopold Hertz 준영 · Aug 14, 2009 · Viewed 121.4k times · Source

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

Answer

Paul Dixon picture Paul Dixon · Aug 14, 2009

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.