Search code examples
phphtmlphp4

Single function to remove all kinds of whitespaces


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


Solution

  • You can doing this using preg_replace():

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