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

How to Remove Control Characters from PHP Strings?

Patricia Arquette
Release: 2024-10-29 11:59:02
Original
1101 people have browsed it

How to Remove Control Characters from PHP Strings?

Removing Control Characters from PHP Strings

To remove control characters like STX from a PHP string, you can utilize a regular expression that specifically targets these characters without affecting other valid characters in the string.

One effective approach is to use a character class that includes the range of control characters you want to remove. In ASCII, control characters occupy the first 32 characters and x7F. Therefore, you can use the following regular expression:

<code class="php">preg_replace('/[\x00-\x1F\x7F]/', '', $input);</code>
Copy after login

This expression will match and remove all control characters from the $input string.

If you want to preserve line feeds and carriage returns, you can modify the regular expression as follows:

<code class="php">preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $input);</code>
Copy after login

This extended expression excludes line feeds (x0A) and carriage returns (x0D) from the removal process.

Note: Ensure to use preg_replace instead of ereg_replace, as ereg_replace is deprecated and removed in later versions of PHP.

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