Home >Backend Development >PHP Tutorial >How to Remove All Whitespace Characters from a String in PHP?
Many programming languages provide built-in functions for stripping whitespace characters from a string. In PHP, there are two common approaches: using the php_strip_whitespace function or regular expressions with preg_replace.
Despite its name, the php_strip_whitespace function only removes spaces, tabs, and newlines (n), leaving other whitespace characters untouched (e.g., non-breaking spaces).
For a more comprehensive approach, regular expressions can be used to strip all whitespace characters. The following expression replaces any sequence of whitespace characters (s ) with an empty string:
$str = preg_replace('/\s+/', '', $str);
This method effectively eliminates all whitespace characters, regardless of their type.
Note that the regular expression above handles whitespace in the ASCII character set. For UTF-8 strings, a more comprehensive expression is required, as discussed in this related answer:
[Handling whitespace in UTF-8 strings with PHP](https://stackoverflow.com/a/22475166/3005479)
The above is the detailed content of How to Remove All Whitespace Characters from a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!