2

I need a php function to remove all the whitespaces in a string.

I tried str_replace(" ","",$str);

Then I tried rtrim();

But even then I can't remove the spaces that are formed by the  

I tried str_replace(" ","",$str);, but its not working.

Then I googled somehow and found out

$converted = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
    $converted = trim($converted);
    $str = trim($converted, "\xA0");

But that is also not working in some cases. Can somebody provide a simple function for removing all the whitespaces.

Thank You

Geo Paul
  • 1,777
  • 6
  • 25
  • 50

4 Answers4

2

You can doing this using preg_replace():

$str = preg_replace('/\s+/', '', $str); // \s matches any whitespace character
2

try this:

$string = trim( preg_replace( '/\s+/si', '', $string ), '' );
Alex
  • 1,630
  • 1
  • 20
  • 31
1

You should use preg_replace

preg_replace('/\s+/', '', $string);
Lao
  • 191
  • 3
1

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

http://php.net/manual/en/function.preg-replace.php

rogal111
  • 5,874
  • 2
  • 27
  • 33