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>
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>
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!