Home >Backend Development >PHP Tutorial >How to Selectively Remove Control Characters from PHP Strings?

How to Selectively Remove Control Characters from PHP Strings?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 05:21:30692browse

How to Selectively Remove Control Characters from PHP Strings?

Eliminating Control Characters from PHP Strings

When working with PHP strings, it is sometimes necessary to remove control characters like STX. While attempting to use preg_replace, you may have found that it removed excessive characters beyond control characters. Our focus here is to show you how to selectively remove only control characters.

To achieve this, you can utilize the following code:

preg_replace('/[\x00-\x1F\x7F]/', '', $input);

This pattern matches and replaces characters from the range of hexadecimal values x00 to x1F, as well as the value x7F. This range encompasses the first 32 ASCII characters as well as the DEL character.

If you want to preserve certain control characters, such as line feed and carriage return, you can adjust the pattern accordingly:

preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $input);

By using this pattern, you can remove all control characters except line feed (n) and carriage return (r).

It is important to note that ereg_replace is deprecated in PHP >= 5.3.0 and removed in PHP >= 7.0.0. To ensure compatibility, use preg_replace instead:

preg_replace('/[[:cntrl:]]/', '', $input);

The above is the detailed content of How to Selectively Remove Control Characters from PHP Strings?. 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