Home  >  Article  >  Backend Development  >  How to Effectively Strip Whitespace Characters from a String in PHP?

How to Effectively Strip Whitespace Characters from a String in PHP?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 09:15:03133browse

How to Effectively Strip Whitespace Characters from a String in PHP?

Stripping Whitespace Characters from a String in PHP

The removal of whitespace characters from a string is a common programming task. In PHP, this can be accomplished using various methods.

One unsuccessful approach is to employ the php_strip_whitespace function, which does not seem to function as intended. Another attempt using the preg_replace function with a simple expression to target whitespace (" ") also proved unsuccessful.

To effectively strip all whitespace characters, regardless of their type or encoding, a more robust regular expression is required:

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

This expression employs the s pattern, which matches one or more sequences of whitespace characters. By replacing these matches with an empty string, all whitespace is removed from the input string $str.

UTF-8 whitespace characters can also be handled using the following approach:

// Handle UTF-8 whitespace characters
$str = iconv('UTF-8', 'ISO-8859-1//IGNORE', $str);
$str = preg_replace('/\s+/', '', $str);
$str = iconv('ISO-8859-1', 'UTF-8', $str);

The above is the detailed content of How to Effectively Strip Whitespace Characters from a String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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