Home > Backend Development > PHP Tutorial > How to Remove All Whitespace Characters from a String in PHP?

How to Remove All Whitespace Characters from a String in PHP?

Linda Hamilton
Release: 2024-11-14 13:25:02
Original
727 people have browsed it

How to Remove All Whitespace Characters from a String in PHP?

Eliminating All Whitespace Characters from a String

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.

php_strip_whitespace

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

Regular Expressions with preg_replace

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);
Copy after login

This method effectively eliminates all whitespace characters, regardless of their type.

Advanced Considerations

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template