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

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

Patricia Arquette
Release: 2024-11-17 09:15:03
Original
209 people have browsed it

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

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

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!

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