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);
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3